diff --git a/.github/workflows/csharp-rest-nuget.yml b/.github/workflows/csharp-rest-nuget.yml new file mode 100644 index 0000000000..24cfde9e4d --- /dev/null +++ b/.github/workflows/csharp-rest-nuget.yml @@ -0,0 +1,29 @@ +name: Publish csharp-rest package +on: + release: + types: [created] + push: + branches: + - master +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: data-api/csharp-rest + steps: + - uses: actions/checkout@v2 + + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Dotnet restore + run: dotnet restore + + - name: Dotnet build + run: dotnet build + + - name: Publish Nuget + run: dotnet nuget push **/*.nupkg --api-key ${{ secrets.NUGET_APIKEY }} --source https://api.nuget.org/v3/index.json || exit 0 diff --git a/.github/workflows/csharp-ws-nuget.yml b/.github/workflows/csharp-ws-nuget.yml new file mode 100644 index 0000000000..0ee7bcc232 --- /dev/null +++ b/.github/workflows/csharp-ws-nuget.yml @@ -0,0 +1,29 @@ +name: Publish csharp-ws package +on: + release: + types: [created] + push: + branches: + - master +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: data-api/csharp-ws + steps: + - uses: actions/checkout@v2 + + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Dotnet restore + run: dotnet restore + + - name: Dotnet build + run: dotnet build + + - name: Publish Nuget + run: dotnet nuget push **/*.nupkg --api-key ${{ secrets.NUGET_APIKEY }} --source https://api.nuget.org/v3/index.json || exit 0 diff --git a/.github/workflows/java-rest-github.yml b/.github/workflows/java-rest-github.yml new file mode 100644 index 0000000000..3b1ba376fb --- /dev/null +++ b/.github/workflows/java-rest-github.yml @@ -0,0 +1,25 @@ +name: Publish java-rest package to the GitHub Packages +on: + release: + types: [created] + push: + branches: + - master +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: data-api/java-rest + steps: + - uses: actions/checkout@v2 + + - name: Set up Java for publishing to GitHub Packages + uses: actions/setup-java@v1 + with: + java-version: 1.8 + + - name: Publish to GitHub Packages + run: mvn -B deploy -DskipTests || exit 0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/java-ws-github.yml b/.github/workflows/java-ws-github.yml new file mode 100644 index 0000000000..6f25ba250b --- /dev/null +++ b/.github/workflows/java-ws-github.yml @@ -0,0 +1,25 @@ +name: Publish java-websocket package to the GitHub Packages +on: + release: + types: [created] + push: + branches: + - master +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: data-api/java-websocket + steps: + - uses: actions/checkout@v2 + + - name: Set up Java for publishing to GitHub Packages + uses: actions/setup-java@v1 + with: + java-version: 1.8 + + - name: Publish to GitHub Packages + run: mvn -B deploy -DskipTests || exit 0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/python-rest-nuget.yml b/.github/workflows/python-rest-nuget.yml new file mode 100644 index 0000000000..49e48d0b6a --- /dev/null +++ b/.github/workflows/python-rest-nuget.yml @@ -0,0 +1,30 @@ +name: Publish python-rest package to the PyPi +on: + release: + types: [created] + push: + branches: + - master +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: data-api/python-rest + steps: + - uses: actions/checkout@v2 + + - name: Set up python + uses: actions/setup-python@v2 + with: + python-version: '3.7' + + - name: install + run: python -m pip install --user --upgrade setuptools wheel twine + + - name: setup package + run: python setup.py sdist bdist_wheel + + - name: deploy + run: python -m twine upload dist/* -u __token__ -p ${{ secrets.PYPI_TOKEN }} || exit 0 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..dac0cc168b --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +################################################################################ +# This .gitignore file was automatically created by Microsoft(R) Visual Studio. +################################################################################ + +/csharp-ws/CoinApi.WEBSOCKET/.vs/CoinApi.WEBSOCKET/v16 +.idea +**/target + +# Visual Studo 2015 cache/options directory +.vs/ \ No newline at end of file diff --git a/LICENSE b/LICENSE index 0aff3cdafa..9602bc4567 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 MARMOT SOLUTIONS LTD +Copyright (c) 2017 COINAPI LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 50accfd0f4..3c13aa7624 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,32 @@ -# CoinAPI-SDK +# CoinAPI-SDK + +![GitHub language count](https://img.shields.io/github/languages/count/coinapi/coinapi-sdk) Welcome to the CoinAPI SDK. This repository contain SDK for our API documented at https://docs.coinapi.io/ -In this repository you can find libraries that will help you use our API with minimal development effort from: +## Repository organization + +Directory | Description | +--- | --- | +data-api | SDK for CoinAPI Market Data API +ems-cloud-mgmt-sdk | SDK for CoinAPI Execution Management System Managed Cloud REST API +ems-gateway-rest-sdk | SDK for CoinAPI Execution Management System REST API +ems-gateway-fix | SDK for CoinAPI Execution Management System FIX API +cryptotick-samples | Examples related to processing CryptoTick GZIP+CSV flat files + +## Package managers coverage + +Language | Package manager | Protocol | Package name | Version/Link | +--- | --- | --- | --- | --- | +C# | NuGet | REST | CoinAPI.REST.V1 | ![Nuget](https://img.shields.io/nuget/v/CoinAPI.REST.v1) | +C# | NuGet | WebSocket | CoinAPI.WebSocket.V1 | ![Nuget](https://img.shields.io/nuget/v/CoinAPI.WebSocket.v1) | +Java | Maven
(GitHub Packages) | REST | io.coinapi.rest.v1 | https://github.com/coinapi/coinapi-sdk/packages/397337 | +Java | Maven
(GitHub Packages) | WebSocket | io.coinapi.websocket.v1 | https://github.com/coinapi/coinapi-sdk/packages/397352 | +Python3 | PyPI | REST | coinapi.rest.v1 | ![PyPI](https://img.shields.io/pypi/v/coinapi.rest.v1) | + +## Language coverage + +In this repository you can find libraries that will help you use our API with minimal development effort from languages like: * Python * R * Matlab @@ -18,5 +42,7 @@ In this repository you can find libraries that will help you use our API with mi * PHP * Haskell * Objective-C + * Swift + +Feel free to make Pull Request with proposed changes or create an Issue on which we respond as soon as possible. -If you spot something wrong, feel free to make Pull Request with proposed changes or create an Issue on which we respond as soon as possible and in less than 24 hours. diff --git a/cpp-rest/README.MD b/cpp-rest/README.MD deleted file mode 100644 index 000e574684..0000000000 --- a/cpp-rest/README.MD +++ /dev/null @@ -1,11 +0,0 @@ -To run examples: - -```bash -cd /path/to/workspace -git clone https://github.com/coinapi/coinapi-sdk -cd coinapi-sdk/cpp-rest -apt-get install libcpprest-dev -# update your API key inside coin_api_test.cpp -make -./coin_api_test -``` diff --git a/cpp-rest/coin_api.h b/cpp-rest/coin_api.h deleted file mode 100644 index 01dc7e05d4..0000000000 --- a/cpp-rest/coin_api.h +++ /dev/null @@ -1,1682 +0,0 @@ -#ifndef _COIN_REST_API_ -#define _COIN_REST_API_ - -#include -#include - - -#define TIME_BUFFER_CAPACITY 64 - -#include -#include -#include -#include -#include - -namespace cpp_rest { - - class coin_api_exception : public std::exception { - private: - int code; - public: - coin_api_exception(int code) : std::exception() { - this->code = code; - } - - virtual const char* what() const noexcept { - switch(code) { - case 400: - return "Bad request"; - break; - case 401: - return "Key is wrong"; - break; - case 403: - return "Key doesnt\'t have enough privileges to access this resource"; - break; - case 404: - return "Not found"; - break; - case 500: - return "Server error"; - break; - case 429: - return "Exceeded API key rate limits"; - break; - default: - return "Unknown"; - break; - } - } - }; - - namespace response { - - struct precise_time { - int year; - int month; - int day; - int hours; - int minutes; - int seconds; - int nanoseconds; - - precise_time() { - this->year = 0; - this->month = 0; - this->day = 0; - this->hours = 0; - this->minutes = 0; - this->seconds = 0; - this->nanoseconds = 0; - } - - precise_time(int year, int month, int day, int hours, int minutes, int seconds, int nanoseconds) { - this->year = year; - this->month = month; - this->day = day; - this->hours = hours; - this->minutes = minutes; - this->seconds = seconds; - this->nanoseconds = nanoseconds; - } - - precise_time(int year, int month, int day, int hours, int minutes, int seconds) { - this->year = year; - this->month = month; - this->day = day; - this->hours = hours; - this->minutes = minutes; - this->seconds = seconds; - this->nanoseconds = 0; - } - }; - - - struct exchange { - std::string exchange_id; // Our exchange identifier - std::string name; // Display name of the exchange - std::string website; // Exchange website address - }; - - struct asset { - std::string asset_id; // Our asset identifier. Superset of the ISO 4217 currency codes standard. - std::string name; // Display name of the asset. - bool type_is_crypto; // true for cryptocurrency assets, false otherwise. - }; - - enum SYMBOL_TYPE { - SYMBOL_TYPE_INVALID, // Reserverd value for invalid data - SYMBOL_TYPE_SPOT, // FX Spot Agreement to exchange one asset for another one (e.g. Buy BTC for USD) - SYMBOL_TYPE_FUTURES, // Futures contract FX Spot derivative contract where traders agree to trade fx spot at predetermined future time - SYMBOL_TYPE_OPTION // Option contract FX Spot derivative contract where traders agree to trade right to require buy or sell of fx spot at agreed price on exercise date - }; - - enum OPTION_EXERCISE_STYLE { - OPTION_EXERCISE_INVALID, - OPTION_EXERCISE_AMERICAN, - OPTION_EXERCISE_EUROPEAN - }; - - struct symbol { - std::string symbol_id; // Our symbol identifier, see table below for format description. - std::string exchange_id; // Our identifier of the exchange where symbol is traded. - SYMBOL_TYPE symbol_type; // Type of symbol (possible values are: SPOT, FUTURES or OPTION) - std::string asset_id_base; // FX Spot base asset identifier, for derivatives it's contact underlying (e.g. BTC for BTC/USD) - std::string asset_id_quote; // FX Spot quote asset identifier, for derivatives it's contract underlying (e.g. USD for BTC/USD) - - bool option_type_is_call; // Boolean value representing option type. true for Call options, false for Put options - double option_strike_price; // Price at which option contract can be exercised - double option_contract_unit; // Base asset amount of underlying spot which single option represents - OPTION_EXERCISE_STYLE option_exercise_style; // Option exercise style. Can be EUROPEAN or AMERICAN - precise_time option_expiration_time; // Option contract expiration time in ISO 8601 - precise_time future_delivery_time; // Predetermined time of futures contract delivery date in ISO 8601 - }; - - struct exchange_rate { - precise_time time; // Time in ISO 8601 of the market data used to calculate exchange rate - std::string asset_id_base; // Exchange rate base asset identifier - std::string asset_id_quote; // Exchange rate quote asset identifier - double rate; // Exchange rate between assets - }; - - enum PERIOD_IDENTIFIER { - PERIOD_INVALID, - PERIOD_1SEC, - PERIOD_2SEC, - PERIOD_3SEC, - PERIOD_4SEC, - PERIOD_5SEC, - PERIOD_6SEC, - PERIOD_10SEC, - PERIOD_15SEC, - PERIOD_20SEC, - PERIOD_30SEC, - PERIOD_1MIN, - PERIOD_2MIN, - PERIOD_3MIN, - PERIOD_4MIN, - PERIOD_5MIN, - PERIOD_6MIN, - PERIOD_10MIN, - PERIOD_15MIN, - PERIOD_20MIN, - PERIOD_30MIN, - PERIOD_1HRS, - PERIOD_2HRS, - PERIOD_3HRS, - PERIOD_4HRS, - PERIOD_6HRS, - PERIOD_8HRS, - PERIOD_12HRS, - PERIOD_1DAY, - PERIOD_2DAY, - PERIOD_3DAY, - PERIOD_5DAY, - PERIOD_7DAY, - PERIOD_10DAY, - PERIOD_1MTH, - PERIOD_2MTH, - PERIOD_3MTH, - PERIOD_4MTH, - PERIOD_6MTH, - PERIOD_1YRS, - PERIOD_2YRS, - PERIOD_3YRS, - PERIOD_4YRS, - PERIOD_5YRS - }; - - enum TRADE_SIDE { - TRADE_SIDE_INVALID, - TRADE_SIDE_BUY, - TRADE_SIDE_SELL, - TRADE_SIDE_BUY_ESTIMATED, - TRADE_SIDE_SELL_ESTIMATED, - TRADE_SIDE_UNKNOWN - }; - - struct period { - PERIOD_IDENTIFIER period_id; // Period identifier, used in other API calls - int length_seconds; // Seconds part of period length - int length_months; // Months part of period length - int unit_count; // Period length in units - std::string unit_name; // Type of unit (second/minute/hour/day/month/year) - std::string display_name; // Display name of period length - }; - - struct timedata { - precise_time time_period_start; // Period starting time (range left inclusive) - precise_time time_period_end; // Period ending time (range right exclusive) - precise_time time_open; // Time of first trade inside period range - precise_time time_close; // Time of last trade inside period range - double price_open; // First trade price inside period range - double price_high; // Highest traded price inside period range - double price_low; // Lowest traded price inside period range - double price_close; // Last trade price inside period range - double volume_traded; // Cumulative base amount traded inside period range - int trades_count; // Amount of trades executed inside period range - }; - - struct trade { - std::string symbol_id; // Our symbol identifier - precise_time time_exchange; // Time of trade reported by exchange - precise_time time_coinapi; // Time when coinapi first received trade from exchange - std::string uuid; // Our trade unique identifier in form of UUIDv4 - double price; // Price of the transaction - double size; // Base asset amount traded in the transaction - TRADE_SIDE taker_side; //Aggressor side of the transaction (BUY/SELL/BUY_ESTIMATED/SELL_ESTIMATED/UNKNOWN) - }; - - struct quote { - std::string symbol_id; // Our symbol identifier - precise_time time_exchange; // Exchange time of orderbook - precise_time time_coinapi; // CoinAPI time when orderbook received from exchange - double ask_price; // Best asking price - double ask_size; // Volume resting on best ask - double bid_price; // Best bidding price - double bid_size; // Volume resting on best bid - }; - - struct quote_with_trade { - struct quote quote; - trade last_trade; // Last executed transaction - }; - - struct level { - double price; // Price of bid/ask - double size; // Volume resting on bid/ask level in base amount - }; - - struct orderbook { - std::string symbol_id; // Our symbol identifier - precise_time time_exchange; // Exchange time of orderbook - precise_time time_coinapi; // CoinAPI time when orderbook received from exchange - std::vector bids; // Best 20 bid levels in order from best to worst - std::vector asks; // Best 20 ask levels in order from best to worst - }; - - - struct twitter_user { - long long id; - std::string id_str; - std::string name; - std::string screen_name; - std::string location; - std::string url; - std::string description; - bool protected_user; - bool verified_user; - int followers_count; - int friends_count; - int listed_count; - int favourites_count; - int statuses_count; - std::string created_at; - int utc_offset; - std::string time_zone; - bool geo_enabled; - std::string lang; - bool contributors_enabled; - bool is_translator; - std::string profile_background_color; - std::string profile_background_image_url; - std::string profile_background_image_url_https; - bool profile_background_tile; - std::string profile_link_color; - std::string profile_sidebar_border_color; - std::string profile_sidebar_fill_color; - std::string profile_text_color; - bool profile_use_background_image; - std::string profile_image_url; - std::string profile_image_url_https; - std::string profile_banner_url; - bool default_profile; - bool default_profile_image; - }; - - struct twitter_hashtag { - std::string text; - std::vector indices; - }; - - struct twitter_symbol { - std::string text; - std::vector indices; - }; - - struct twitter_url { - std::string display_url; - std::string url; - std::string expanded_url; - std::vector indices; - }; - - struct twitter_user_mention { - long long id; - std::string id_str; - std::string name; - std::string screen_name; - std::vector indices; - }; - - struct twitter_size { - int w; - int h; - std::string resize; - }; - - struct twitter_sizes { - struct twitter_size small; - struct twitter_size medium; - struct twitter_size large; - struct twitter_size thumb; - }; - - struct twitter_media { - long long id; - std::string id_str; - std::vector indices; - std::string media_url; - std::string media_url_https; - std::string url; - std::string display_url; - std::string expanded_url; - std::string type; - twitter_sizes sizes; - }; - - struct twitter_entities { - std::vector hashtags; - std::vector urls; - std::vector user_mentions; - std::vector symbols; - std::vector media; - }; - - struct twitter { - std::string created_at; - long long id; - std::string id_str; - std::string text; - std::string source; - bool truncated; - - std::vector display_text_range; - - long long in_reply_to_status_id; - std::string in_reply_to_status_id_str; - long long in_reply_to_user_id; - std::string in_reply_to_user_id_str; - std::string in_reply_to_screen_name; - - bool in_reply_to_status_id_is_null; - bool in_reply_to_status_id_str_is_null; - bool in_reply_to_user_id_is_null; - bool in_reply_to_user_id_str_is_null; - bool in_reply_to_screen_name_is_null; - - twitter_user user; - twitter_entities entities; - - bool is_quote_status; - int retweet_count; - int favorite_count; - - bool favorited; - bool retweeted; - bool possibly_sensitive; - std::string filter_level; - std::string lang; - std::string timestamp_ms; - }; - - typedef std::vector exchanges; - typedef std::vector assets; - typedef std::vector symbols; - typedef std::vector exchange_rates; - typedef std::vector periods; - typedef std::vector timeseries; - typedef std::vector trades; - typedef std::vector quotes; - typedef std::vector quotes_with_trade; - typedef std::vector orderbooks; - typedef std::vector twitters; - } - - class coin_api { - private: - std::wstring key; - - pplx::task get_json(const utility::string_t & path_query_fragment) const { - web::http::client::http_client_config client_config; - - web::http::http_request msg(web::http::methods::GET); - std::string str_key(key.begin(), key.end()); - - msg.set_request_uri(path_query_fragment); - msg.headers().add(U("X-CoinAPI-Key"), utility::string_t(str_key.c_str())); - - // used for debug purposes - //std::wcout << "path_query_fragment: " << path_query_fragment.c_str() << std::endl; - - web::http::client::http_client client(U("https://rest.coinapi.io/"), client_config); - return client.request(msg).then([=](web::http::http_response response) -> pplx::task { - if(response.status_code() == web::http::status_codes::OK) { - return response.extract_json(); - } - else { - throw coin_api_exception(response.status_code()); - } - // Handle error cases, for now return empty json value... - return pplx::task_from_result(web::json::value()); - }); - } - - static response::precise_time parseISO8601time(const std::string& iso8601time) { - response::precise_time result; - sscanf(iso8601time.c_str(), "%d-%d-%dT%d:%d:%d.%dZ", &result.year, &result.month, &result.day, &result.hours, &result.minutes, &result.seconds, &result.nanoseconds); - result.nanoseconds *= 100; - return result; - } - - static std::string iso8601time_to_str(const response::precise_time& time, bool nanoseconds = true) { - char time_Buffer[TIME_BUFFER_CAPACITY]; - if (nanoseconds) - sprintf(time_Buffer, "%04d-%02d-%02dT%02d:%02d:%02d.%07d", time.year, time.month, time.day, time.hours, time.minutes, time.seconds, time.nanoseconds/100); - else - sprintf(time_Buffer, "%04d-%02d-%02dT%02d:%02d:%02d", time.year, time.month, time.day, time.hours, time.minutes, time.seconds); - return time_Buffer; - } - - static void parse_exchange_rate(response::exchange_rate& result, const web::json::value& exchangerate_entry) { - if (exchangerate_entry.has_field("asset_id_base")) - result.asset_id_base = exchangerate_entry.as_object().at("asset_id_base").as_string().c_str(); - result.asset_id_quote = exchangerate_entry.as_object().at("asset_id_quote").as_string().c_str(); - result.rate = exchangerate_entry.as_object().at("rate").as_double(); - - std::string time = exchangerate_entry.as_object().at("time").as_string().c_str(); - result.time = parseISO8601time(time); - } - - static void parse_timeseries(response::timeseries& timeseries, const web::json::value& json_response) { - if (json_response.is_array()) { - for(size_t i=0; i& result, const web::json::value& json_response) { - if (json_response.is_array()) { - for(size_t i=0; ikey = std::wstring(key.begin(), key.end()); - } - - coin_api(const std::wstring& key) { - this->key = key; - } - - // Get a detailed list of exchanges provided by the system. - pplx::task metadata_list_all_exchanges() { - return get_json(web::uri_builder(U("/v1/exchanges")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::exchanges result; - - if (json_response.is_array()) { - for(size_t i=0; i metadata_list_all_assets() { - return get_json(web::uri_builder(U("/v1/assets")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::assets result; - - if (json_response.is_array()) { - for(size_t i=0; i metadata_list_all_symbols() { - return get_json(web::uri_builder(U("/v1/symbols")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::symbols result; - - if (json_response.is_array()) { - for(size_t i=0; i get_exchange_rate(std::string asset_id_base, std::string asset_id_quote) { - utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).append_path(asset_id_quote.c_str()).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::exchange_rate result; - parse_exchange_rate(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get exchange rate between pair of requested assets at specific time. - // asset_id_base Requested exchange rate base asset identifier. - // asset_id_quote Requested exchange rate quote asset identifier. - // time Time at which exchange rate is calculated - pplx::task get_exchange_rate(std::string asset_id_base, std::string asset_id_quote, const response::precise_time& time) { - utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).append_path(asset_id_quote.c_str()).append_query(U("time"), iso8601time_to_str(time)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::exchange_rate result; - parse_exchange_rate(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get the current exchange rate between requested asset and all other assets. - // asset_id_base Requested exchange rates base asset identifier - pplx::task get_all_exchange_rates(std::string asset_id_base) { - utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::exchange_rates result; - std::string response_id_base = json_response.as_object().at("asset_id_base").as_string().c_str(); - - web::json::value& rates_array = json_response.as_object().at("rates"); - if (rates_array.is_array()) { - for(size_t i=0; i ohlcv_list_all_periods() { - return get_json(web::uri_builder(U("/v1/ohlcv/periods")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::periods result; - - if (json_response.is_array()) { - for(size_t i=0; i ohlcv_get_latest_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("period_id"), period_to_str(period).c_str()).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task ohlcv_get_latest_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, int limit) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get OHLCV timeseries data for requested symbol and period, returned in time ascending order. - pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, int limit) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, const response::precise_time& time_end) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { - utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::timeseries result; - parse_timeseries(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get latest trades from all symbols up to 1 minute ago or get latest trades from a specific symbol without time limitation. - // Latest data is always returned in time descending order. - pplx::task trades_get_latest_data() { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(U("latest")).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_latest_data(int limit) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_latest_data(std::string symbol) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_latest_data(std::string symbol, int limit) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { - utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::trades result; - parse_trades(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get current quotes for all symbols - pplx::task quotes_get_for_all_symbols() { - return get_json(web::uri_builder(U("/v1/quotes/current")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::quotes_with_trade result; - - if (json_response.is_array()) { - for(size_t i=0; i quotes_get_for_symbol(std::string symbol) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("current")).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::quote_with_trade result; - - //std::wcout << json_response.as_string().c_str(); - - if (json_response.is_object()) { - parse_quote(result.quote, json_response); - if (json_response.has_field("last_trade")) - parse_trade(result.last_trade, json_response.as_object().at("last_trade"), false); - } - - return pplx::task_from_result(result); - }); - } - - // Get latest quote updates up to 1 minute ago or get updates for a specific symbol without time limit. - // Latest data is always returned in time descending order. - pplx::task quotes_get_latest_data() { - return get_json(web::uri_builder(U("/v1/quotes/latest")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - - if (json_response.is_array()) { - for(size_t i=0; i quotes_get_latest_data(int limit) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - - if (json_response.is_array()) { - for(size_t i=0; i quotes_get_latest_data(std::string symbol) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - - if (json_response.is_array()) { - for(size_t i=0; i quotes_get_latest_data(std::string symbol, int limit) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - - if (json_response.is_array()) { - for(size_t i=0; i quotes_get_historical_data(std::string symbol, const response::precise_time& time_start) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - parse_quotes(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - parse_quotes(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - parse_quotes(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { - utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::quotes result; - parse_quotes(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get current orderbook snapshot for all symbols - pplx::task orderbooks_get_for_all_symbols() { - return get_json(web::uri_builder(U("/v1/orderbooks/current")).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get current orderbook snapshot for specific symbol - pplx::task orderbooks_get_for_symbol(std::string symbol) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("current")).to_string(); - return get_json(url).then([](web::json::value json_response) -> pplx::task { - response::orderbook result; - parse_orderbook(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get latest orderbook snapshots for a specific symbol, returned in time descending order. - pplx::task orderbooks_get_latest_data(std::string symbol) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task orderbooks_get_latest_data(std::string symbol, int limit) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get historical orderbook snapshots for a specific symbol within time range, returned in time ascending order. - pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { - utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { - response::orderbooks result; - parse_orderbooks(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get latest tweets related to cryptocurrency markets, returned in time descending order. - pplx::task twitter_get_latest_data() { - return get_json(web::uri_builder(U("/v1/twitter/latest")).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - //std::wcout << "twitter_get_latest_data " << result.size() << std::endl; - return pplx::task_from_result(result); - }); - } - - pplx::task twitter_get_latest_data(int limit) { - utility::string_t url = web::uri_builder(U("/v1/twitter")).append_path(U("latest")).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - return pplx::task_from_result(result); - }); - } - - // Get historical tweets related to cryptocurrency markets, returned in time ascending order. - pplx::task twitter_get_historical_data(const response::precise_time& time_start) { - utility::string_t url = web::uri_builder(U("/v1/twitter")).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); - return get_json(web::uri_builder(url).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task twitter_get_historical_data(const response::precise_time& time_start, int limit) { - utility::string_t url = web::uri_builder(U("/v1/twitter")).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task twitter_get_historical_data(const response::precise_time& time_start, const response::precise_time& time_end) { - utility::string_t url = web::uri_builder(U("/v1/twitter")).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); - return get_json(web::uri_builder(url).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - return pplx::task_from_result(result); - }); - } - - pplx::task twitter_get_historical_data(const response::precise_time& time_start, const response::precise_time& time_end, int limit) { - utility::string_t url = web::uri_builder(U("/v1/twitter")).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); - return get_json(web::uri_builder(url).to_string()).then([=](web::json::value json_response) -> pplx::task { - response::twitters result; - parse_twitters(result, json_response); - return pplx::task_from_result(result); - }); - } - }; -} - -#endif - diff --git a/cryptotick-samples/limitbook_full_l2l3/.gitattributes b/cryptotick-samples/limitbook_full_l2l3/.gitattributes new file mode 100644 index 0000000000..1ff0c42304 --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/cryptotick-samples/limitbook_full_l2l3/.gitignore b/cryptotick-samples/limitbook_full_l2l3/.gitignore new file mode 100644 index 0000000000..4ce6fddec9 --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/.gitignore @@ -0,0 +1,340 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- Backup*.rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb \ No newline at end of file diff --git a/cryptotick-samples/limitbook_full_l2l3/27606-BITSTAMP_SPOT_BTC_EUR.csv.gz b/cryptotick-samples/limitbook_full_l2l3/27606-BITSTAMP_SPOT_BTC_EUR.csv.gz new file mode 100644 index 0000000000..e55a7d7e9d Binary files /dev/null and b/cryptotick-samples/limitbook_full_l2l3/27606-BITSTAMP_SPOT_BTC_EUR.csv.gz differ diff --git a/cryptotick-samples/limitbook_full_l2l3/4365242-COINBASE_SPOT_ETC_BTC.csv.gz b/cryptotick-samples/limitbook_full_l2l3/4365242-COINBASE_SPOT_ETC_BTC.csv.gz new file mode 100644 index 0000000000..dd8a16e80a Binary files /dev/null and b/cryptotick-samples/limitbook_full_l2l3/4365242-COINBASE_SPOT_ETC_BTC.csv.gz differ diff --git a/cryptotick-samples/limitbook_full_l2l3/Program.cs b/cryptotick-samples/limitbook_full_l2l3/Program.cs new file mode 100644 index 0000000000..59aafe389c --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/Program.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.IO.Compression; + +namespace limitbook_full_l2 +{ + class Program + { + public enum ELimitUpdateType + { + ADD, + SET, + SUB, + SNAPSHOT, + DELETE, + MATCH + } + + public static string dateFormat = "HH:mm:ss.fffffff"; + public static int bufferSize = 1 * 1024 * 1024; // 1MB + + static void Main(string[] args) + { + string path = args.Length > 0 ? args[0] : "4365242-COINBASE_SPOT_ETC_BTC.csv.gz"; + + using (GZipStream gz = + new GZipStream( + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize), + CompressionMode.Decompress)) + { + using (StreamReader sr = new StreamReader(gz)) + { + ProcessReader(dateFormat, sr); + } + } + } + + private static void ProcessReader(string dateFormat, StreamReader sr) + { + string line; + var book = new Dictionary<(bool, decimal, string), decimal>(); + DateTime lastTimeExchange = DateTime.MinValue; + ELimitUpdateType? prevType = null; + + // skip header + sr.ReadLine(); + + while ((line = sr.ReadLine()) != null) + { + // parse columns + var columns = line.Split(new char[] { ';' }); + var time_exchange = DateTime.ParseExact(columns[0], dateFormat, CultureInfo.InvariantCulture); + var time_coinapi = DateTime.ParseExact(columns[1], dateFormat, CultureInfo.InvariantCulture); + var type = (ELimitUpdateType)Enum.Parse(typeof(ELimitUpdateType), columns[2]); + var isSellAsk = int.Parse(columns[3]) == 0; + var price = decimal.Parse(columns[4], NumberStyles.Float, CultureInfo.InvariantCulture); + var size = decimal.Parse(columns[5], NumberStyles.Float, CultureInfo.InvariantCulture); + var order_id = columns.Length > 6 ? columns[6] : ""; + + // process snapshot book cleaning + if (type == ELimitUpdateType.SNAPSHOT && prevType.HasValue && prevType.Value != ELimitUpdateType.SNAPSHOT) + { + book.Clear(); + } + prevType = type; + + // process specific order types + if (type == ELimitUpdateType.SNAPSHOT || type == ELimitUpdateType.SET) + { + book[(isSellAsk, price, order_id)] = size; + } + else if (type == ELimitUpdateType.ADD) + { + if (!book.ContainsKey((isSellAsk, price, order_id))) + { + book[(isSellAsk, price, order_id)] = size; + } + else + { + book[(isSellAsk, price, order_id)] = book[(isSellAsk, price, order_id)] + size; + } + } + else if (type == ELimitUpdateType.SUB || type == ELimitUpdateType.DELETE || type == ELimitUpdateType.MATCH) + { + if (!book.ContainsKey((isSellAsk, price, order_id))) + { + book[(isSellAsk, price, order_id)] = 0; + } + else + { + var newSize = book[(isSellAsk, price, order_id)] - size; + book[(isSellAsk, price, order_id)] = newSize >= 0 ? newSize : 0; + } + } + else + { + throw new ArgumentException(nameof(type)); + } + + // remove empty levels + if (book.ContainsKey((isSellAsk, price, order_id)) && book[(isSellAsk, price, order_id)] <= 0) + { + book.Remove((isSellAsk, price, order_id)); + } + + // process book feed forward + if (time_exchange > lastTimeExchange) + { + ProcessOrderbook(time_exchange, time_coinapi, book); + lastTimeExchange = time_exchange; + } + } + } + + private static void ProcessOrderbook(DateTime time_exchange, DateTime time_coinapi, Dictionary<(bool, decimal, string), decimal> book) + { + // processing work + var recv_diff = time_coinapi - time_exchange; + Console.WriteLine($"{time_exchange} (recv: {(int)recv_diff.TotalMilliseconds}): levels {book.Count}"); + } + } +} diff --git a/cryptotick-samples/limitbook_full_l2l3/Properties/launchSettings.json b/cryptotick-samples/limitbook_full_l2l3/Properties/launchSettings.json new file mode 100644 index 0000000000..b03e835ec6 --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/Properties/launchSettings.json @@ -0,0 +1,7 @@ +{ + "profiles": { + "ConsoleApp1": { + "commandName": "Project" + } + } +} \ No newline at end of file diff --git a/cryptotick-samples/limitbook_full_l2l3/README.md b/cryptotick-samples/limitbook_full_l2l3/README.md new file mode 100644 index 0000000000..43806bec9d --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/README.md @@ -0,0 +1 @@ +Examples related to processing the flat files acquired from the www.cryptotick.com website. \ No newline at end of file diff --git a/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.csproj b/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.csproj new file mode 100644 index 0000000000..7b1cefb615 --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.csproj @@ -0,0 +1,18 @@ + + + + Exe + netcoreapp2.2 + limitbook_full_l2.Program + + + + + PreserveNewest + + + Always + + + + diff --git a/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.sln b/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.sln new file mode 100644 index 0000000000..cc7d9b699b --- /dev/null +++ b/cryptotick-samples/limitbook_full_l2l3/limitbook_full_l2l3.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30717.126 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "limitbook_full_l2l3", "limitbook_full_l2l3.csproj", "{4F5425E5-DE39-497D-867F-37B38316E5B2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4F5425E5-DE39-497D-867F-37B38316E5B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F5425E5-DE39-497D-867F-37B38316E5B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F5425E5-DE39-497D-867F-37B38316E5B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F5425E5-DE39-497D-867F-37B38316E5B2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B47CE903-BF3E-43CC-9C77-B55AC6D41558} + EndGlobalSection +EndGlobal diff --git a/csharp-fix/App.config b/csharp-fix/App.config deleted file mode 100644 index 8227adb989..0000000000 --- a/csharp-fix/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/csharp-fix/MarketDataApp.cs b/csharp-fix/MarketDataApp.cs deleted file mode 100644 index e47b1feeee..0000000000 --- a/csharp-fix/MarketDataApp.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using QuickFix; -using QuickFix.Fields; -using System.Collections.Generic; - -namespace csharp_fix -{ - public class MarketDataApp : QuickFix.MessageCracker, QuickFix.IApplication - { - Session _session = null; - - #region IApplication interface overrides - - public void OnCreate(SessionID sessionID) - { - _session = Session.LookupSession(sessionID); - } - - public void OnLogon(SessionID sessionID) - { - Console.WriteLine("Logon - " + sessionID.ToString()); - } - public void OnLogout(SessionID sessionID) - { - Console.WriteLine("Logout - " + sessionID.ToString()); - } - - public void FromAdmin(Message message, SessionID sessionID) - { - } - public void ToAdmin(Message message, SessionID sessionID) - { - } - - public void FromApp(Message message, SessionID sessionID) - { - Console.WriteLine("IN: " + message.ToString()); - try - { - Crack(message, sessionID); - } - catch (Exception ex) - { - Console.WriteLine("==Cracker exception=="); - Console.WriteLine(ex.ToString()); - Console.WriteLine(ex.StackTrace); - } - } - - public void ToApp(Message message, SessionID sessionID) - { - Console.WriteLine("OUT: " + message.ToString()); - } - #endregion - - public void OnMessage(QuickFix.FIX44.MarketDataIncrementalRefresh msg, - SessionID s) - { - for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx ++) - { - var trade = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup(); - msg.GetGroup(idx + 1, trade); - - Console.WriteLine($"Trade {trade.MDUpdateAction} @ {trade.Symbol}:"); - Console.WriteLine($" ID: {trade.MDEntryID}"); - Console.WriteLine($" Date: {trade.MDEntryDate}"); - Console.WriteLine($" Time: {trade.MDEntryTime}"); - Console.WriteLine($" Px: {trade.MDEntryPx}"); - Console.WriteLine($" Size: {trade.MDEntrySize}"); - Console.WriteLine($" TakerSide: {trade.MDEntryOriginator}"); - } - Console.WriteLine($"--------------------------------------------------"); - } - - public void OnMessage(QuickFix.FIX44.MarketDataSnapshotFullRefresh msg, - SessionID s) - { - for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) - { - var level = new QuickFix.FIX44.MarketDataSnapshotFullRefresh.NoMDEntriesGroup(); - msg.GetGroup(idx + 1, level); - Console.WriteLine($"Orderbook {level.MDEntryType} @ {msg.Symbol}:"); - Console.WriteLine($" Date: {level.MDEntryDate}"); - Console.WriteLine($" Time: {level.MDEntryTime}"); - Console.WriteLine($" Px: {level.MDEntryPx}"); - Console.WriteLine($" Size: {level.MDEntrySize}"); - } - } - - private void SendMessage(Message m) - { - if (_session != null) - _session.Send(m); - else - { - // This probably won't ever happen. - Console.WriteLine("Can't send message: session not created."); - } - } - } -} \ No newline at end of file diff --git a/csharp-fix/Program.cs b/csharp-fix/Program.cs deleted file mode 100644 index 9c46519ec9..0000000000 --- a/csharp-fix/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_fix -{ - class Program - { - [STAThread] - static void Main(string[] args) - { - try - { - QuickFix.SessionSettings settings = new QuickFix.SessionSettings("config_ssl.cfg"); - MarketDataApp application = new MarketDataApp(); - QuickFix.IMessageStoreFactory storeFactory = new QuickFix.FileStoreFactory(settings); - QuickFix.ILogFactory logFactory = new QuickFix.ScreenLogFactory(settings); - QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, logFactory); - initiator.Start(); - - System.Threading.Thread.Sleep(TimeSpan.MaxValue); - } - catch (System.Exception e) - { - Console.WriteLine(e.Message); - Console.WriteLine(e.StackTrace); - Console.ReadLine(); - } - Environment.Exit(1); - } - } -} diff --git a/csharp-fix/config_ssl.cfg b/csharp-fix/config_ssl.cfg deleted file mode 100644 index 995e69d0ca..0000000000 --- a/csharp-fix/config_ssl.cfg +++ /dev/null @@ -1,24 +0,0 @@ -[DEFAULT] -ConnectionType=initiator -ReconnectInterval=2 -FileStorePath=store -FileLogPath=log -StartTime=00:00:00 -EndTime=00:00:00 -UseDataDictionary=Y -DataDictionary=FIX44.xml -#SocketConnectHost=10.231.0.25 -SocketConnectHost=fix.coinapi.io -SocketConnectPort=3301 -SSLEnable=Y -SSLServerName=fix.coinapi.io -SSLValidateCertificates=Y -SSLCheckCertificateRevocation=Y -LogoutTimeout=5 -ResetOnLogon=Y - -[SESSION] -BeginString=FIX.4.4 -SenderCompID=YOUR_API_KEY_HERE -TargetCompID=COINAPI -HeartBtInt=1 diff --git a/csharp-fix/csharp_fix.csproj b/csharp-fix/csharp_fix.csproj deleted file mode 100644 index 1af4cd17aa..0000000000 --- a/csharp-fix/csharp_fix.csproj +++ /dev/null @@ -1,69 +0,0 @@ - - - - - Debug - AnyCPU - {EE9BC3A5-32F6-4BB7-8751-D80634527705} - Exe - csharp_fix - csharp_fix - v4.5.2 - 512 - true - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - csharp_fix.Program - - - - packages\QuickFix.Net.1.7.0\lib\QuickFix.dll - - - - - - - - - - - - - - - - - - - Always - - - - - - Always - - - - \ No newline at end of file diff --git a/csharp-fix/csharp_fix.sln b/csharp-fix/csharp_fix.sln deleted file mode 100644 index 61d7e8fbf7..0000000000 --- a/csharp-fix/csharp_fix.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26403.7 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharp_fix", "csharp_fix.csproj", "{EE9BC3A5-32F6-4BB7-8751-D80634527705}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/csharp-fix/packages.config b/csharp-fix/packages.config deleted file mode 100644 index 0649f218c8..0000000000 --- a/csharp-fix/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/csharp-rest/App.config b/csharp-rest/App.config deleted file mode 100644 index 88fa4027bd..0000000000 --- a/csharp-rest/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/csharp-rest/CoinApi.cs b/csharp-rest/CoinApi.cs deleted file mode 100644 index bbc9fd7b60..0000000000 --- a/csharp-rest/CoinApi.cs +++ /dev/null @@ -1,234 +0,0 @@ - -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - class CoinApi { - private string apikey; - private string dateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; - private static string WebUrl = "https://rest.coinapi.io";// "https://rest-test.coinapi.io"; - public CoinApi(string apikey) { - this.apikey = apikey; - } - - public T GetData(string url) { - using (HttpClientHandler handler = new HttpClientHandler()) { - handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - using (HttpClient client = new HttpClient(handler, false)) { - - client.DefaultRequestHeaders.Add("X-CoinAPI-Key", apikey); - - var responseFromServer = client.GetAsync(WebUrl + url).Result.Content.ReadAsStringAsync().Result; - var dataFromServer = JsonConvert.DeserializeObject(responseFromServer); - return dataFromServer; - } - } - } - - public List Metadata_list_exchanges() { - return GetData>("/v1/exchanges"); - } - - public List Metadata_list_assets() { - return GetData>("/v1/assets"); - } - public List Metadata_list_symbols() { - return GetData>("/v1/symbols"); - } - - public Exchangerate Exchange_rates_get_specific_rate(string baseId, string quoteId, DateTime time) { - var url = string.Format("/v1/exchangerate/{0}/{1}?time={2}", baseId, quoteId, time.ToString(dateFormat)); - return GetData(url); - } - public Exchangerate Exchange_rates_get_specific_rate(string baseId, string quoteId) { - var url = string.Format("/v1/exchangerate/{0}/{1}", baseId, quoteId); - return GetData(url); - } - - public ExchangeCurrentrate Exchange_rates_get_all_current_rates(string baseId) { - var url = string.Format("/v1/exchangerate/{0}", baseId); - return GetData(url); - } - - public List Ohlcv_list_all_periods() { - var url = "/v1/ohlcv/periods"; - return GetData>(url); - } - - - public List Ohlcv_latest_data(string symbolId, string periodId, int limit) { - var url = string.Format("/v1/ohlcv/{0}/latest?period_id={1}&limit={2}", symbolId, periodId, limit); - return GetData>(url); - } - public List Ohlcv_latest_data(string symbolId, string periodId) { - var url = string.Format("/v1/ohlcv/{0}/latest?period_id={1}", symbolId, periodId); - return GetData>(url); - } - - public List Ohlcv_historical_data(string symbolId, string periodId, DateTime start, DateTime end, int limit) { - var url = string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&time_end={3}&limit={4}", symbolId, periodId, start.ToString("yyyy-MM-dd HH:ss:mm"), end.ToString("yyyy-MM-dd HH:ss:mm"), limit); - return GetData>(url); - } - public List Ohlcv_historical_data(string symbolId, string periodId, DateTime start, DateTime end) { - var url = string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&time_end={3}", symbolId, periodId, start.ToString(dateFormat), end.ToString(dateFormat)); - return GetData>(url); - } - public List Ohlcv_historical_data(string symbolId, string periodId, DateTime start, int limit) { - var url = string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&limit={3}", symbolId, periodId, start.ToString(dateFormat), limit); - return GetData>(url); - } - public List Ohlcv_historical_data(string symbolId, string periodId, DateTime start) { - var url = string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}", symbolId, periodId, start.ToString(dateFormat)); - return GetData>(url); - } - - public List Trades_latest_data_all() { - var url = "/v1/trades/latest"; - return GetData>(url); - } - public List Trades_latest_data_all(int limit) { - var url = string.Format("/v1/trades/latest?limit={0}", limit); - return GetData>(url); - } - - - public List Trades_latest_data_symbol(string symbolId) { - var url = string.Format("/v1/trades/{0}/latest", symbolId); - return GetData>(url); - } - public List Trades_latest_data_symbol(string symbolId, int limit) { - var url = string.Format("/v1/trades/{0}/latest?limit={1}", symbolId, limit); - return GetData>(url); - } - - public List Trades_historical_data(string symbolId, DateTime start, DateTime end, int limit) { - var url = string.Format("/v1/trades/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat), limit); - return GetData>(url); - } - public List Trades_historical_data(string symbolId, DateTime start) { - var url = string.Format("/v1/trades/{0}/history?time_start={1}", symbolId, start.ToString(dateFormat)); - return GetData>(url); - } - public List Trades_historical_data(string symbolId, DateTime start, DateTime end) { - var url = string.Format("/v1/trades/{0}/history?time_start={1}&time_end={2}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat)); - return GetData>(url); - } - public List Trades_historical_data(string symbolId, DateTime start, int limit) { - var url = string.Format("/v1/trades/{0}/history?time_start={1}&limit={2}", symbolId, start.ToString(dateFormat), limit); - return GetData>(url); - } - - public List Quotes_current_data_all() { - var url = "/v1/quotes/current"; - return GetData>(url); - } - - public Quote Quotes_current_data_symbol(string symbolId) { - var url = string.Format("/v1/quotes/{0}/current", symbolId); - return GetData(url); - } - - public List Quotes_latest_data_all() { - var url = "/v1/quotes/latest"; - return GetData>(url); - } - public List Quotes_latest_data_all(int limit) { - var url = string.Format("/v1/quotes/latest?limit={0}", limit); - return GetData>(url); - } - - public List Quotes_latest_data_symbol(string symbolId) { - var url = string.Format("/v1/quotes/{0}/latest", symbolId); - return GetData>(url); - } - public List Quotes_latest_data_symbol(string symbolId, int limit) { - var url = string.Format("/v1/quotes/{0}/latest?limit={1}", symbolId, limit); - return GetData>(url); - } - - public List Quotes_historical_data(string symbolId, DateTime start, DateTime end, int limit) { - var url = string.Format("/v1/quotes/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat), limit); - return GetData>(url); - - } - public List Quotes_historical_data(string symbolId, DateTime start) { - var url = string.Format("/v1/quotes/{0}/history?time_start={1}", symbolId, start.ToString(dateFormat)); - return GetData>(url); - } - public List Quotes_historical_data(string symbolId, DateTime start, DateTime end) { - var url = string.Format("/v1/quotes/{0}/history?time_start={1}&time_end={2}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat)); - return GetData>(url); - } - public List Quotes_historical_data(string symbolId, DateTime start, int limit) { - var url = string.Format("/v1/quotes/{0}/history?time_start={1}&limit={2}", symbolId, start.ToString(dateFormat), limit); - return GetData>(url); - - } - public List Orderbooks_current_data_all() { - var url = "/v1/orderbooks/current"; - return GetData>(url); - } - - public Orderbook Orderbooks_current_data_symbol(string symbolId) { - var url = string.Format("/v1/orderbooks/{0}/current", symbolId); - return GetData(url); - } - - public List Orderbooks_last_data(string symbolId, int limit) { - var url = string.Format("/v1/orderbooks/{0}/latest?limit={1}", symbolId, limit); - return GetData>(url); - } - public List Orderbooks_last_data(string symbolId) { - var url = string.Format("/v1/orderbooks/{0}/latest", symbolId); - return GetData>(url); - } - - public List Orderbooks_historical_data(string symbolId, DateTime start, DateTime end, int limit) { - var url = string.Format("/v1/orderbooks/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat), limit); - return GetData>(url); - } - public List Orderbooks_historical_data(string symbolId, DateTime start) { - var url = string.Format("/v1/orderbooks/{0}/history?time_start={1}", symbolId, start.ToString(dateFormat)); - return GetData>(url); - } - public List Orderbooks_historical_data(string symbolId, DateTime start, DateTime end) { - var url = string.Format("/v1/orderbooks/{0}/history?time_start={1}&time_end={2}", symbolId, start.ToString(dateFormat), end.ToString(dateFormat)); - return GetData>(url); - } - public List Orderbooks_historical_data(string symbolId, DateTime start, int limit) { - var url = string.Format("/v1/orderbooks/{0}/history?time_start={1}&limit={2}", symbolId, start.ToString(dateFormat), limit); - return GetData>(url); - } - public List Twitter_last_data(int limit) { - var url = string.Format("/v1/twitter/latest?limit={0}", limit); - return GetData>(url); - } - public List Twitter_last_data() { - var url = "/v1/twitter/latest"; - return GetData>(url); - } - public List Twitter_historical_data(DateTime start, DateTime end, int limit) { - var url = string.Format("/v1/twitter/history?time_start={0}&time_end={1}&limit={2}", start.ToString(dateFormat), end.ToString(dateFormat), limit); - return GetData>(url); - } - public List Twitter_historical_data(DateTime start) { - var url = string.Format("/v1/twitter/history?time_start={0}", start.ToString(dateFormat)); - return GetData>(url); - } - public List Twitter_historical_data(DateTime start, DateTime end) { - var url = string.Format("/v1/twitter/history?time_start={0}&time_end={1}", start.ToString(dateFormat), end.ToString(dateFormat)); - return GetData>(url); - } - public List Twitter_historical_data(DateTime start, int limit) { - var url = string.Format("/v1/twitter/history?time_start={0}&limit={1}", start.ToString(dateFormat), limit); - return GetData>(url); - } - } - -} diff --git a/csharp-rest/DataModels/Asset.cs b/csharp-rest/DataModels/Asset.cs deleted file mode 100644 index 7235a9327f..0000000000 --- a/csharp-rest/DataModels/Asset.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Asset { - - - public string asset_id { get; set; } - public string name { get; set; } - public bool type_is_crypto { get; set; } - - - } -} diff --git a/csharp-rest/DataModels/Entities.cs b/csharp-rest/DataModels/Entities.cs deleted file mode 100644 index af6014fffa..0000000000 --- a/csharp-rest/DataModels/Entities.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Entities { - public Hashtag[] hashtags { get; set; } - public User_Mentions[] user_mentions { get; set; } - public Url[] urls { get; set; } - } -} diff --git a/csharp-rest/DataModels/Exchange.cs b/csharp-rest/DataModels/Exchange.cs deleted file mode 100644 index 6694d91157..0000000000 --- a/csharp-rest/DataModels/Exchange.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Exchange { - public string exchange_id { get; set; } - public string website { get; set; } - public string name { get; set; } - } -} diff --git a/csharp-rest/DataModels/Hashtag.cs b/csharp-rest/DataModels/Hashtag.cs deleted file mode 100644 index a66534fc98..0000000000 --- a/csharp-rest/DataModels/Hashtag.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Hashtag { - public string text { get; set; } - public long[] indices { get; set; } - } -} diff --git a/csharp-rest/DataModels/OHLCV.cs b/csharp-rest/DataModels/OHLCV.cs deleted file mode 100644 index 216b1b0209..0000000000 --- a/csharp-rest/DataModels/OHLCV.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class OHLCV { - public DateTime time_period_start { get; set; } - public DateTime time_period_end { get; set; } - public DateTime time_open { get; set; } - public DateTime time_close { get; set; } - public decimal price_open { get; set; } - public decimal price_high { get; set; } - public decimal price_low { get; set; } - public decimal price_close { get; set; } - public decimal volume_traded { get; set; } - public int trades_count { get; set; } - } -} diff --git a/csharp-rest/DataModels/Quote.cs b/csharp-rest/DataModels/Quote.cs deleted file mode 100644 index eace2cb5f4..0000000000 --- a/csharp-rest/DataModels/Quote.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Quote { - public string symbol_id { get; set; } - public DateTime time_exchange { get; set; } - public DateTime time_coinapi { get; set; } - public decimal ask_price { get; set; } - public decimal ask_size { get; set; } - public decimal bid_price { get; set; } - public decimal bid_size { get; set; } - public Trade last_trade { get; set; } - } -} diff --git a/csharp-rest/DataModels/Symbol.cs b/csharp-rest/DataModels/Symbol.cs deleted file mode 100644 index bc59972de3..0000000000 --- a/csharp-rest/DataModels/Symbol.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Symbol { - public string symbol_id { get; set; } - public string exchange_id { get; set; } - public string symbol_type { get; set; } - public bool option_type_is_call { get; set; } - public decimal option_strike_price { get; set; } - public decimal option_contract_unit { get; set; } - public string option_exercise_style { get; set; } - public DateTime option_expiration_time { get; set; } - public DateTime future_delivery_time { get; set; } - public string asset_id_base { get; set; } - public string asset_id_quote { get; set; } - } -} diff --git a/csharp-rest/DataModels/Trade.cs b/csharp-rest/DataModels/Trade.cs deleted file mode 100644 index fce53fdde7..0000000000 --- a/csharp-rest/DataModels/Trade.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Trade { - public string symbol_id { get; set; } - public DateTime time_exchange { get; set; } - public DateTime time_coinapi { get; set; } - public string uuid { get; set; } - public decimal price { get; set; } - public decimal size { get; set; } - public string taker_side { get; set; } - } - -} diff --git a/csharp-rest/DataModels/Twitter.cs b/csharp-rest/DataModels/Twitter.cs deleted file mode 100644 index decfa4adb4..0000000000 --- a/csharp-rest/DataModels/Twitter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Twitter { - public long? in_reply_to_status_id { get; set; } - public string text { get; set; } - public string in_reply_to_screen_name { get; set; } - public bool truncated { get; set; } - public bool retweeted { get; set; } - public string in_reply_to_status_id_str { get; set; } - public string source { get; set; } - public string created_at { get; set; } - public string in_reply_to_user_id_str { get; set; } - public object geo { get; set; } - public long retweet_count { get; set; } - public object contributors { get; set; } - public string id_str { get; set; } - public Entities entities { get; set; } - public object place { get; set; } - public object coordinates { get; set; } - public User user { get; set; } - public long? in_reply_to_user_id { get; set; } - public long id { get; set; } - public bool favorited { get; set; } - public bool possibly_sensitive { get; set; } - } -} diff --git a/csharp-rest/DataModels/Url.cs b/csharp-rest/DataModels/Url.cs deleted file mode 100644 index 00131d56de..0000000000 --- a/csharp-rest/DataModels/Url.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class Url { - public long[] indices { get; set; } - public string display_url { get; set; } - public string url { get; set; } - public string expanded_url { get; set; } - } -} diff --git a/csharp-rest/DataModels/User.cs b/csharp-rest/DataModels/User.cs deleted file mode 100644 index 442d37813e..0000000000 --- a/csharp-rest/DataModels/User.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class User { - public object following { get; set; } - public object notifications { get; set; } - public bool profile_background_tile { get; set; } - public bool contributors_enabled { get; set; } - public bool verified { get; set; } - public long friends_count { get; set; } - public bool is_translator { get; set; } - public string profile_background_image_url_https { get; set; } - public string profile_link_color { get; set; } - public long listed_count { get; set; } - public string profile_sidebar_border_color { get; set; } - public string profile_image_url { get; set; } - public string description { get; set; } - public long favourites_count { get; set; } - public string created_at { get; set; } - public bool default_profile { get; set; } - public bool profile_use_background_image { get; set; } - public bool show_all_inline_media { get; set; } - public bool geo_enabled { get; set; } - public string time_zone { get; set; } - public string profile_background_color { get; set; } - public bool default_profile_image { get; set; } - public string profile_background_image_url { get; set; } - public long followers_count { get; set; } - public bool _protected { get; set; } - public string url { get; set; } - public string profile_image_url_https { get; set; } - public string id_str { get; set; } - public string lang { get; set; } - public string name { get; set; } - public long statuses_count { get; set; } - public string profile_text_color { get; set; } - public long id { get; set; } - public object follow_request_sent { get; set; } - public long? utc_offset { get; set; } - public string profile_sidebar_fill_color { get; set; } - public string location { get; set; } - public string screen_name { get; set; } - } - -} diff --git a/csharp-rest/DataModels/User_Mentions.cs b/csharp-rest/DataModels/User_Mentions.cs deleted file mode 100644 index b94cab67f2..0000000000 --- a/csharp-rest/DataModels/User_Mentions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - public class User_Mentions { - public long[] indices { get; set; } - public string name { get; set; } - public string id_str { get; set; } - public long id { get; set; } - public string screen_name { get; set; } - } -} diff --git a/csharp-rest/Program.cs b/csharp-rest/Program.cs deleted file mode 100644 index 239e45db6b..0000000000 --- a/csharp-rest/Program.cs +++ /dev/null @@ -1,537 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace csharp_rest { - class Program { - static void Main(string[] args) { - var coinApi = new CoinApi("YOUR_API_KEY_HERE"); - Console.Write("Exchange:"); - Console.Write(Environment.NewLine); - var exchange = coinApi.Metadata_list_exchanges(); - foreach (var item in exchange) { - Console.Write("exchange_id:" + item.exchange_id); - Console.Write(Environment.NewLine); - Console.Write("website:" + item.website); - Console.Write(Environment.NewLine); - Console.Write("name:" + item.name); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("symbols:"); - Console.Write(Environment.NewLine); - var symbols = coinApi.Metadata_list_symbols(); - foreach (var item in symbols) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("exchange_id:" + item.exchange_id); - Console.Write(Environment.NewLine); - Console.Write("symbol_type:" + item.symbol_type); - Console.Write(Environment.NewLine); - - if (item.symbol_type == "OPTION") - { - Console.Write("option_type_is_call:" + item.option_type_is_call); - Console.Write(Environment.NewLine); - Console.Write("option_strike_price:" + item.option_strike_price); - Console.Write(Environment.NewLine); - Console.Write("option_contract_unit:" + item.option_contract_unit); - Console.Write(Environment.NewLine); - Console.Write("option_exercise_style:" + item.option_exercise_style); - Console.Write(Environment.NewLine); - Console.Write("option_expiration_time:" + item.option_expiration_time); - Console.Write(Environment.NewLine); - } - - if (item.symbol_type == "FUTURES") - { - Console.Write("future_delivery_time:" + item.future_delivery_time); - Console.Write(Environment.NewLine); - } - - Console.Write("asset_id_base:" + item.asset_id_base); - Console.Write(Environment.NewLine); - Console.Write("asset_id_quote:" + item.asset_id_quote); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - - Console.Write("Asset:"); - Console.Write(Environment.NewLine); - var assets = coinApi.Metadata_list_assets(); - foreach (var item in assets) { - Console.Write("asset_id:" + item.asset_id); - Console.Write(Environment.NewLine); - Console.Write("name:" + item.name); - Console.Write(Environment.NewLine); - Console.Write("type_is_crypto:" + item.type_is_crypto); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Exchangerate:"); - Console.Write(Environment.NewLine); - var exchange_rate = coinApi.Exchange_rates_get_specific_rate("BTC", "USD"); - - Console.Write("time:" + exchange_rate.time); - Console.Write(Environment.NewLine); - Console.Write("asset_id_base:" + exchange_rate.asset_id_base); - Console.Write(Environment.NewLine); - Console.Write("asset_id_quote:" + exchange_rate.asset_id_quote); - Console.Write(Environment.NewLine); - Console.Write("rate:" + exchange_rate.rate); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - - Console.Write("Exchangerate Last Week:"); - Console.Write(Environment.NewLine); - var lastweek = DateTime.Now.AddDays(-7); - var exchange_rate_last_week = coinApi.Exchange_rates_get_specific_rate("BTC", "USD", lastweek); - Console.Write("time:" + exchange_rate_last_week.time); - Console.Write(Environment.NewLine); - Console.Write("asset_id_base:" + exchange_rate_last_week.asset_id_base); - Console.Write(Environment.NewLine); - Console.Write("asset_id_quote:" + exchange_rate_last_week.asset_id_quote); - Console.Write(Environment.NewLine); - Console.Write("rate:" + exchange_rate_last_week.rate); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - - Console.Write("Exchangerate current rates:"); - Console.Write(Environment.NewLine); - var current_rates = coinApi.Exchange_rates_get_all_current_rates("BTC"); - - Console.Write("Asset ID Base:" + current_rates.asset_id_base); - Console.Write(Environment.NewLine); - foreach (var item in current_rates.rates) { - Console.Write("time:" + item.time); - Console.Write(Environment.NewLine); - Console.Write("asset_id_quote:" + item.asset_id_quote); - Console.Write(Environment.NewLine); - Console.Write("rate:" + item.rate); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Ohlcv list all periods:"); - Console.Write(Environment.NewLine); - var periods = coinApi.Ohlcv_list_all_periods(); - foreach (var item in periods) { - Console.Write("period_id:" + item.period_id); - Console.Write(Environment.NewLine); - Console.Write("length_seconds:" + item.length_seconds); - Console.Write(Environment.NewLine); - Console.Write("length_months:" + item.length_months); - Console.Write(Environment.NewLine); - Console.Write("unit_count:" + item.unit_count); - Console.Write(Environment.NewLine); - Console.Write("unit_name:" + item.unit_name); - Console.Write(Environment.NewLine); - Console.Write("display_name:" + item.display_name); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Ohlcv latest data:"); - Console.Write(Environment.NewLine); - var ohlcv_latest = coinApi.Ohlcv_latest_data("BITSTAMP_SPOT_BTC_USD", "1MIN"); - - foreach (var item in ohlcv_latest) { - Console.Write("time_period_start:" + item.time_period_start); - Console.Write(Environment.NewLine); - Console.Write("time_period_end:" + item.time_period_end); - Console.Write(Environment.NewLine); - Console.Write("time_open:" + item.time_open); - Console.Write(Environment.NewLine); - Console.Write("time_close:" + item.time_close); - Console.Write(Environment.NewLine); - Console.Write("price_open:" + item.price_open); - Console.Write(Environment.NewLine); - Console.Write("price_high:" + item.price_high); - Console.Write(Environment.NewLine); - Console.Write("price_low:" + item.price_low); - Console.Write(Environment.NewLine); - Console.Write("price_close:" + item.price_close); - Console.Write(Environment.NewLine); - Console.Write("volume_traded:" + item.volume_traded); - Console.Write(Environment.NewLine); - Console.Write("trades_count:" + item.trades_count); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Ohlcv last year:"); - Console.Write(Environment.NewLine); - var start_of_2016 = new DateTime(2016, 1, 1); - var ohlcv_historical = coinApi.Ohlcv_historical_data("BITSTAMP_SPOT_BTC_USD", "1MIN", start_of_2016); - foreach (var item in ohlcv_historical) { - Console.Write("time_period_start:" + item.time_period_start); - Console.Write(Environment.NewLine); - Console.Write("time_period_end:" + item.time_period_end); - Console.Write(Environment.NewLine); - Console.Write("time_open:" + item.time_open); - Console.Write(Environment.NewLine); - Console.Write("time_close:" + item.time_close); - Console.Write(Environment.NewLine); - Console.Write("price_open:" + item.price_open); - Console.Write(Environment.NewLine); - Console.Write("price_high:" + item.price_high); - Console.Write(Environment.NewLine); - Console.Write("price_low:" + item.price_low); - Console.Write(Environment.NewLine); - Console.Write("price_close:" + item.price_close); - Console.Write(Environment.NewLine); - Console.Write("volume_traded:" + item.volume_traded); - Console.Write(Environment.NewLine); - Console.Write("trades_count:" + item.trades_count); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Trades latest data all:"); - Console.Write(Environment.NewLine); - var latest_trades = coinApi.Trades_latest_data_all(); - - foreach (var item in latest_trades) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("uuid:" + item.uuid); - Console.Write(Environment.NewLine); - Console.Write("price:" + item.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + item.size); - Console.Write(Environment.NewLine); - Console.Write("taker_side:" + item.taker_side); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Trades latest data symbol:"); - Console.Write(Environment.NewLine); - var latest_trades_doge = coinApi.Trades_latest_data_symbol("BITTREX_SPOT_BTC_DOGE"); - foreach (var item in latest_trades_doge) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("uuid:" + item.uuid); - Console.Write(Environment.NewLine); - Console.Write("price:" + item.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + item.size); - Console.Write(Environment.NewLine); - Console.Write("taker_side:" + item.taker_side); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Trades historical data:"); - Console.Write(Environment.NewLine); - var historical_trades_btc = coinApi.Trades_historical_data("BITSTAMP_SPOT_BTC_USD", start_of_2016); - foreach (var item in historical_trades_btc) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("uuid:" + item.uuid); - Console.Write(Environment.NewLine); - Console.Write("price:" + item.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + item.size); - Console.Write(Environment.NewLine); - Console.Write("taker_side:" + item.taker_side); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - Console.Write("Quotes current data all:"); - Console.Write(Environment.NewLine); - var current_quotes = coinApi.Quotes_current_data_all(); - foreach (var item in current_quotes) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("ask_price:" + item.ask_price); - Console.Write(Environment.NewLine); - Console.Write("ask_size:" + item.ask_size); - Console.Write(Environment.NewLine); - Console.Write("bid_price:" + item.bid_price); - Console.Write(Environment.NewLine); - Console.Write("bid_size:" + item.bid_size); - Console.Write(Environment.NewLine); - //Console.Write("last_trade:" + item.last_trade); - //Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - Console.Write("Quotes current data symbol:"); - Console.Write(Environment.NewLine); - var current_quote_btc_usd = coinApi.Quotes_current_data_symbol("BITSTAMP_SPOT_BTC_USD"); - - Console.Write("symbol_id:" + current_quote_btc_usd.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + current_quote_btc_usd.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + current_quote_btc_usd.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("ask_price:" + current_quote_btc_usd.ask_price); - Console.Write(Environment.NewLine); - Console.Write("ask_size:" + current_quote_btc_usd.ask_size); - Console.Write(Environment.NewLine); - Console.Write("bid_price:" + current_quote_btc_usd.bid_price); - Console.Write(Environment.NewLine); - Console.Write("bid_size:" + current_quote_btc_usd.bid_size); - Console.Write(Environment.NewLine); - if (current_quote_btc_usd.last_trade != null) { - Console.Write("last trade:"); - Console.Write(Environment.NewLine); - Console.Write("symbol_id:" + current_quote_btc_usd.last_trade.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + current_quote_btc_usd.last_trade.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + current_quote_btc_usd.last_trade.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("uuid:" + current_quote_btc_usd.last_trade.uuid); - Console.Write(Environment.NewLine); - Console.Write("price:" + current_quote_btc_usd.last_trade.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + current_quote_btc_usd.last_trade.size); - Console.Write(Environment.NewLine); - Console.Write("taker_side:" + current_quote_btc_usd.last_trade.taker_side); - Console.Write(Environment.NewLine); - } - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - - Console.Write("Quotes latest data all:"); - Console.Write(Environment.NewLine); - var quotes_latest_data = coinApi.Quotes_latest_data_all(); - foreach (var item in quotes_latest_data) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("ask_price:" + item.ask_price); - Console.Write(Environment.NewLine); - Console.Write("ask_size:" + item.ask_size); - Console.Write(Environment.NewLine); - Console.Write("bid_price:" + item.bid_price); - Console.Write(Environment.NewLine); - Console.Write("bid_size:" + item.bid_size); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - Console.Write("Quotes latest data symbol:"); - Console.Write(Environment.NewLine); - var quotes_latest_data_btc_usd = coinApi.Quotes_latest_data_symbol("BITSTAMP_SPOT_BTC_USD"); - foreach (var item in quotes_latest_data_btc_usd) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("ask_price:" + item.ask_price); - Console.Write(Environment.NewLine); - Console.Write("ask_size:" + item.ask_size); - Console.Write(Environment.NewLine); - Console.Write("bid_price:" + item.bid_price); - Console.Write(Environment.NewLine); - Console.Write("bid_size:" + item.bid_size); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - Console.Write("Quotes historical data:"); - Console.Write(Environment.NewLine); - var quotes_historical_data_btc_usd = coinApi.Quotes_historical_data("BITSTAMP_SPOT_BTC_USD", start_of_2016); - foreach (var item in quotes_historical_data_btc_usd) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - Console.Write("ask_price:" + item.ask_price); - Console.Write(Environment.NewLine); - Console.Write("ask_size:" + item.ask_size); - Console.Write(Environment.NewLine); - Console.Write("bid_price:" + item.bid_price); - Console.Write(Environment.NewLine); - Console.Write("bid_size:" + item.bid_size); - Console.Write(Environment.NewLine); - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - Console.Write("Orderbooks current data all:"); - Console.Write(Environment.NewLine); - var orderbooks_current_data = coinApi.Orderbooks_current_data_all(); - foreach (var item in orderbooks_current_data) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - - Console.Write("Asks:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.asks) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - Console.Write("Bids:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.bids) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Orderbooks current data symbol:"); - Console.Write(Environment.NewLine); - var orderbooks_current_data_btc_usd = coinApi.Orderbooks_current_data_symbol("BITSTAMP_SPOT_BTC_USD"); - Console.Write("symbol_id:" + orderbooks_current_data_btc_usd.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + orderbooks_current_data_btc_usd.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + orderbooks_current_data_btc_usd.time_coinapi); - Console.Write(Environment.NewLine); - - Console.Write("Asks:"); - Console.Write(Environment.NewLine); - foreach (var itm in orderbooks_current_data_btc_usd.asks) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - Console.Write("Bids:"); - Console.Write(Environment.NewLine); - foreach (var itm in orderbooks_current_data_btc_usd.bids) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - - Console.Write("Orderbooks last data:"); - Console.Write(Environment.NewLine); - var orderbooks_latest_data_btc_usd = coinApi.Orderbooks_last_data("BITSTAMP_SPOT_BTC_USD"); - foreach (var item in orderbooks_latest_data_btc_usd) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - - Console.Write("Asks:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.asks) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - Console.Write("Bids:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.bids) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - Console.Write("Orderbooks historical data:"); - Console.Write(Environment.NewLine); - var orderbooks_historical_data_btc_usd = coinApi.Orderbooks_historical_data("BITSTAMP_SPOT_BTC_USD", start_of_2016); - foreach (var item in orderbooks_historical_data_btc_usd) { - Console.Write("symbol_id:" + item.symbol_id); - Console.Write(Environment.NewLine); - Console.Write("time_exchange:" + item.time_exchange); - Console.Write(Environment.NewLine); - Console.Write("time_coinapi:" + item.time_coinapi); - Console.Write(Environment.NewLine); - - Console.Write("Asks:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.asks) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - Console.Write("Bids:"); - Console.Write(Environment.NewLine); - foreach (var itm in item.bids) { - Console.Write("price:" + itm.price); - Console.Write(Environment.NewLine); - Console.Write("size:" + itm.size); - Console.Write(Environment.NewLine); - - } - - Console.Write("--------------------------------------------------------------------------------------------------------"); - Console.Write(Environment.NewLine); - } - - var twitter_latest_data = coinApi.Twitter_last_data(); - var twitter_historical_data = coinApi.Twitter_historical_data(start_of_2016); - - - - Console.ReadLine(); - } - } -} diff --git a/csharp-rest/Properties/AssemblyInfo.cs b/csharp-rest/Properties/AssemblyInfo.cs deleted file mode 100644 index 0d84d69236..0000000000 --- a/csharp-rest/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("csharp-rest")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("csharp-rest")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e7d2bce4-b23e-4bdb-8836-d4dbb267b87b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-rest/csharp-rest.csproj b/csharp-rest/csharp-rest.csproj deleted file mode 100644 index 5f6457b5be..0000000000 --- a/csharp-rest/csharp-rest.csproj +++ /dev/null @@ -1,85 +0,0 @@ - - - - - Debug - AnyCPU - {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B} - Exe - Properties - csharp_rest - csharp-rest - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/csharp-rest/csharp-rest.sln b/csharp-rest/csharp-rest.sln deleted file mode 100644 index 05dc7e36b0..0000000000 --- a/csharp-rest/csharp-rest.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26403.7 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharp-rest", "csharp-rest.csproj", "{E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/csharp-rest/packages.config b/csharp-rest/packages.config deleted file mode 100644 index c8092071ed..0000000000 --- a/csharp-rest/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/data-api/LICENSE b/data-api/LICENSE new file mode 100644 index 0000000000..9602bc4567 --- /dev/null +++ b/data-api/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 COINAPI LTD + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data-api/README.md b/data-api/README.md new file mode 100644 index 0000000000..0ca73fd49a --- /dev/null +++ b/data-api/README.md @@ -0,0 +1,16 @@ +# CoinAPI Market Data SDK + +## WebSocket connection example + + 1. Download `wscat` npm package (https://www.npmjs.com/package/wscat) using `npm install -g wscat` command + 2. Establish connection to us by command `wscat --connect wss://ws.coinapi.io/v1/` + 3. Send this json `{ "type": "hello", "apikey": "TYPE_YOUR_API_KEY_HERE", "heartbeat": false, "subscribe_data_type": ["trade", "quote", "book50"] }` + 4. Right now you are receiving messages + +## Unofficial SDK's + + Feel free to continue the effort to extend the coverage of this SDK. + + * Rust: https://github.com/soerenmartius/coinapi-rs + + diff --git a/data-api/cpp-rest/README.MD b/data-api/cpp-rest/README.MD new file mode 100644 index 0000000000..f2da73aae7 --- /dev/null +++ b/data-api/cpp-rest/README.MD @@ -0,0 +1,11 @@ +To run examples: + +```bash +cd /path/to/workspace +git clone https://github.com/coinapi/coinapi-sdk +cd coinapi-sdk/data-api/cpp-rest +apt-get install libcpprest-dev +# update your API key inside coin_api_test.cpp +make +./coin_api_test +``` diff --git a/data-api/cpp-rest/coin_api.h b/data-api/cpp-rest/coin_api.h new file mode 100644 index 0000000000..9c5bd45c16 --- /dev/null +++ b/data-api/cpp-rest/coin_api.h @@ -0,0 +1,1230 @@ +#ifndef _COIN_REST_API_ +#define _COIN_REST_API_ + +#include +#include + + +#define TIME_BUFFER_CAPACITY 64 + +#include +#include +#include +#include +#include + +namespace cpp_rest { + + class coin_api_exception : public std::exception { + private: + int code; + public: + coin_api_exception(int code) : std::exception() { + this->code = code; + } + + virtual const char* what() const noexcept { + switch(code) { + case 400: + return "Bad request"; + break; + case 401: + return "Key is wrong"; + break; + case 403: + return "Key doesnt\'t have enough privileges to access this resource"; + break; + case 404: + return "Not found"; + break; + case 500: + return "Server error"; + break; + case 429: + return "Exceeded API key rate limits"; + break; + default: + return "Unknown"; + break; + } + } + }; + + namespace response { + + struct precise_time { + int year; + int month; + int day; + int hours; + int minutes; + int seconds; + int nanoseconds; + + precise_time() { + this->year = 0; + this->month = 0; + this->day = 0; + this->hours = 0; + this->minutes = 0; + this->seconds = 0; + this->nanoseconds = 0; + } + + precise_time(int year, int month, int day, int hours, int minutes, int seconds, int nanoseconds) { + this->year = year; + this->month = month; + this->day = day; + this->hours = hours; + this->minutes = minutes; + this->seconds = seconds; + this->nanoseconds = nanoseconds; + } + + precise_time(int year, int month, int day, int hours, int minutes, int seconds) { + this->year = year; + this->month = month; + this->day = day; + this->hours = hours; + this->minutes = minutes; + this->seconds = seconds; + this->nanoseconds = 0; + } + }; + + + struct exchange { + std::string exchange_id; // Our exchange identifier + std::string name; // Display name of the exchange + std::string website; // Exchange website address + }; + + struct asset { + std::string asset_id; // Our asset identifier. Superset of the ISO 4217 currency codes standard. + std::string name; // Display name of the asset. + bool type_is_crypto; // true for cryptocurrency assets, false otherwise. + }; + + enum SYMBOL_TYPE { + SYMBOL_TYPE_INVALID, // Reserverd value for invalid data + SYMBOL_TYPE_SPOT, // FX Spot Agreement to exchange one asset for another one (e.g. Buy BTC for USD) + SYMBOL_TYPE_FUTURES, // Futures contract FX Spot derivative contract where traders agree to trade fx spot at predetermined future time + SYMBOL_TYPE_OPTION // Option contract FX Spot derivative contract where traders agree to trade right to require buy or sell of fx spot at agreed price on exercise date + }; + + enum OPTION_EXERCISE_STYLE { + OPTION_EXERCISE_INVALID, + OPTION_EXERCISE_AMERICAN, + OPTION_EXERCISE_EUROPEAN + }; + + struct symbol { + std::string symbol_id; // Our symbol identifier, see table below for format description. + std::string exchange_id; // Our identifier of the exchange where symbol is traded. + SYMBOL_TYPE symbol_type; // Type of symbol (possible values are: SPOT, FUTURES or OPTION) + std::string asset_id_base; // FX Spot base asset identifier, for derivatives it's contact underlying (e.g. BTC for BTC/USD) + std::string asset_id_quote; // FX Spot quote asset identifier, for derivatives it's contract underlying (e.g. USD for BTC/USD) + + bool option_type_is_call; // Boolean value representing option type. true for Call options, false for Put options + double option_strike_price; // Price at which option contract can be exercised + double option_contract_unit; // Base asset amount of underlying spot which single option represents + OPTION_EXERCISE_STYLE option_exercise_style; // Option exercise style. Can be EUROPEAN or AMERICAN + precise_time option_expiration_time; // Option contract expiration time in ISO 8601 + precise_time future_delivery_time; // Predetermined time of futures contract delivery date in ISO 8601 + }; + + struct exchange_rate { + precise_time time; // Time in ISO 8601 of the market data used to calculate exchange rate + std::string asset_id_base; // Exchange rate base asset identifier + std::string asset_id_quote; // Exchange rate quote asset identifier + double rate; // Exchange rate between assets + }; + + enum PERIOD_IDENTIFIER { + PERIOD_INVALID, + PERIOD_1SEC, + PERIOD_2SEC, + PERIOD_3SEC, + PERIOD_4SEC, + PERIOD_5SEC, + PERIOD_6SEC, + PERIOD_10SEC, + PERIOD_15SEC, + PERIOD_20SEC, + PERIOD_30SEC, + PERIOD_1MIN, + PERIOD_2MIN, + PERIOD_3MIN, + PERIOD_4MIN, + PERIOD_5MIN, + PERIOD_6MIN, + PERIOD_10MIN, + PERIOD_15MIN, + PERIOD_20MIN, + PERIOD_30MIN, + PERIOD_1HRS, + PERIOD_2HRS, + PERIOD_3HRS, + PERIOD_4HRS, + PERIOD_6HRS, + PERIOD_8HRS, + PERIOD_12HRS, + PERIOD_1DAY, + PERIOD_2DAY, + PERIOD_3DAY, + PERIOD_5DAY, + PERIOD_7DAY, + PERIOD_10DAY, + PERIOD_1MTH, + PERIOD_2MTH, + PERIOD_3MTH, + PERIOD_4MTH, + PERIOD_6MTH, + PERIOD_1YRS, + PERIOD_2YRS, + PERIOD_3YRS, + PERIOD_4YRS, + PERIOD_5YRS + }; + + enum TRADE_SIDE { + TRADE_SIDE_INVALID, + TRADE_SIDE_BUY, + TRADE_SIDE_SELL, + TRADE_SIDE_BUY_ESTIMATED, + TRADE_SIDE_SELL_ESTIMATED, + TRADE_SIDE_UNKNOWN + }; + + struct period { + PERIOD_IDENTIFIER period_id; // Period identifier, used in other API calls + int length_seconds; // Seconds part of period length + int length_months; // Months part of period length + int unit_count; // Period length in units + std::string unit_name; // Type of unit (second/minute/hour/day/month/year) + std::string display_name; // Display name of period length + }; + + struct timedata { + precise_time time_period_start; // Period starting time (range left inclusive) + precise_time time_period_end; // Period ending time (range right exclusive) + precise_time time_open; // Time of first trade inside period range + precise_time time_close; // Time of last trade inside period range + double price_open; // First trade price inside period range + double price_high; // Highest traded price inside period range + double price_low; // Lowest traded price inside period range + double price_close; // Last trade price inside period range + double volume_traded; // Cumulative base amount traded inside period range + int trades_count; // Amount of trades executed inside period range + }; + + struct trade { + std::string symbol_id; // Our symbol identifier + precise_time time_exchange; // Time of trade reported by exchange + precise_time time_coinapi; // Time when coinapi first received trade from exchange + std::string uuid; // Our trade unique identifier in form of UUIDv4 + double price; // Price of the transaction + double size; // Base asset amount traded in the transaction + TRADE_SIDE taker_side; //Aggressor side of the transaction (BUY/SELL/BUY_ESTIMATED/SELL_ESTIMATED/UNKNOWN) + }; + + struct quote { + std::string symbol_id; // Our symbol identifier + precise_time time_exchange; // Exchange time of orderbook + precise_time time_coinapi; // CoinAPI time when orderbook received from exchange + double ask_price; // Best asking price + double ask_size; // Volume resting on best ask + double bid_price; // Best bidding price + double bid_size; // Volume resting on best bid + }; + + struct quote_with_trade { + struct quote quote; + trade last_trade; // Last executed transaction + }; + + struct level { + double price; // Price of bid/ask + double size; // Volume resting on bid/ask level in base amount + }; + + struct orderbook { + std::string symbol_id; // Our symbol identifier + precise_time time_exchange; // Exchange time of orderbook + precise_time time_coinapi; // CoinAPI time when orderbook received from exchange + std::vector bids; // Best 20 bid levels in order from best to worst + std::vector asks; // Best 20 ask levels in order from best to worst + }; + + + typedef std::vector exchanges; + typedef std::vector assets; + typedef std::vector symbols; + typedef std::vector exchange_rates; + typedef std::vector periods; + typedef std::vector timeseries; + typedef std::vector trades; + typedef std::vector quotes; + typedef std::vector quotes_with_trade; + typedef std::vector orderbooks; + } + + class coin_api { + private: + std::wstring key; + + pplx::task get_json(const utility::string_t & path_query_fragment) const { + web::http::client::http_client_config client_config; + + web::http::http_request msg(web::http::methods::GET); + std::string str_key(key.begin(), key.end()); + + msg.set_request_uri(path_query_fragment); + msg.headers().add(U("X-CoinAPI-Key"), utility::string_t(str_key.c_str())); + + // used for debug purposes + //std::wcout << "path_query_fragment: " << path_query_fragment.c_str() << std::endl; + + web::http::client::http_client client(U("https://rest.coinapi.io/"), client_config); + return client.request(msg).then([=](web::http::http_response response) -> pplx::task { + if(response.status_code() == web::http::status_codes::OK) { + return response.extract_json(); + } + else { + throw coin_api_exception(response.status_code()); + } + // Handle error cases, for now return empty json value... + return pplx::task_from_result(web::json::value()); + }); + } + + static response::precise_time parseISO8601time(const std::string& iso8601time) { + response::precise_time result; + sscanf(iso8601time.c_str(), "%d-%d-%dT%d:%d:%d.%dZ", &result.year, &result.month, &result.day, &result.hours, &result.minutes, &result.seconds, &result.nanoseconds); + result.nanoseconds *= 100; + return result; + } + + static std::string iso8601time_to_str(const response::precise_time& time, bool nanoseconds = true) { + char time_Buffer[TIME_BUFFER_CAPACITY]; + if (nanoseconds) + sprintf(time_Buffer, "%04d-%02d-%02dT%02d:%02d:%02d.%07d", time.year, time.month, time.day, time.hours, time.minutes, time.seconds, time.nanoseconds/100); + else + sprintf(time_Buffer, "%04d-%02d-%02dT%02d:%02d:%02d", time.year, time.month, time.day, time.hours, time.minutes, time.seconds); + return time_Buffer; + } + + static void parse_exchange_rate(response::exchange_rate& result, const web::json::value& exchangerate_entry) { + if (exchangerate_entry.has_field("asset_id_base")) + result.asset_id_base = exchangerate_entry.as_object().at("asset_id_base").as_string().c_str(); + result.asset_id_quote = exchangerate_entry.as_object().at("asset_id_quote").as_string().c_str(); + result.rate = exchangerate_entry.as_object().at("rate").as_double(); + + std::string time = exchangerate_entry.as_object().at("time").as_string().c_str(); + result.time = parseISO8601time(time); + } + + static void parse_timeseries(response::timeseries& timeseries, const web::json::value& json_response) { + if (json_response.is_array()) { + for(size_t i=0; i& result, const web::json::value& json_response) { + if (json_response.is_array()) { + for(size_t i=0; ikey = std::wstring(key.begin(), key.end()); + } + + coin_api(const std::wstring& key) { + this->key = key; + } + + // Get a detailed list of exchanges provided by the system. + pplx::task metadata_list_all_exchanges() { + return get_json(web::uri_builder(U("/v1/exchanges")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::exchanges result; + + if (json_response.is_array()) { + for(size_t i=0; i metadata_list_all_assets() { + return get_json(web::uri_builder(U("/v1/assets")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::assets result; + + if (json_response.is_array()) { + for(size_t i=0; i metadata_list_all_symbols() { + return get_json(web::uri_builder(U("/v1/symbols")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::symbols result; + + if (json_response.is_array()) { + for(size_t i=0; i get_exchange_rate(std::string asset_id_base, std::string asset_id_quote) { + utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).append_path(asset_id_quote.c_str()).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::exchange_rate result; + parse_exchange_rate(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get exchange rate between pair of requested assets at specific time. + // asset_id_base Requested exchange rate base asset identifier. + // asset_id_quote Requested exchange rate quote asset identifier. + // time Time at which exchange rate is calculated + pplx::task get_exchange_rate(std::string asset_id_base, std::string asset_id_quote, const response::precise_time& time) { + utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).append_path(asset_id_quote.c_str()).append_query(U("time"), iso8601time_to_str(time)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::exchange_rate result; + parse_exchange_rate(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get the current exchange rate between requested asset and all other assets. + // asset_id_base Requested exchange rates base asset identifier + pplx::task get_all_exchange_rates(std::string asset_id_base) { + utility::string_t url = web::uri_builder(U("/v1/exchangerate")).append_path(asset_id_base.c_str()).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::exchange_rates result; + std::string response_id_base = json_response.as_object().at("asset_id_base").as_string().c_str(); + + web::json::value& rates_array = json_response.as_object().at("rates"); + if (rates_array.is_array()) { + for(size_t i=0; i ohlcv_list_all_periods() { + return get_json(web::uri_builder(U("/v1/ohlcv/periods")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::periods result; + + if (json_response.is_array()) { + for(size_t i=0; i ohlcv_get_latest_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("period_id"), period_to_str(period).c_str()).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task ohlcv_get_latest_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, int limit) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get OHLCV timeseries data for requested symbol and period, returned in time ascending order. + pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, int limit) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, const response::precise_time& time_end) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task ohlcv_get_historical_timeseries(std::string symbol, response::PERIOD_IDENTIFIER period, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { + utility::string_t url = web::uri_builder(U("/v1/ohlcv")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("period_id"), period_to_str(period).c_str()).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::timeseries result; + parse_timeseries(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get latest trades from all symbols up to 1 minute ago or get latest trades from a specific symbol without time limitation. + // Latest data is always returned in time descending order. + pplx::task trades_get_latest_data() { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(U("latest")).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_latest_data(int limit) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(U("latest")).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_latest_data(std::string symbol) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_latest_data(std::string symbol, int limit) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task trades_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { + utility::string_t url = web::uri_builder(U("/v1/trades")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::trades result; + parse_trades(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get current quotes for all symbols + pplx::task quotes_get_for_all_symbols() { + return get_json(web::uri_builder(U("/v1/quotes/current")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::quotes_with_trade result; + + if (json_response.is_array()) { + for(size_t i=0; i quotes_get_for_symbol(std::string symbol) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("current")).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::quote_with_trade result; + + //std::wcout << json_response.as_string().c_str(); + + if (json_response.is_object()) { + parse_quote(result.quote, json_response); + if (json_response.has_field("last_trade")) + parse_trade(result.last_trade, json_response.as_object().at("last_trade"), false); + } + + return pplx::task_from_result(result); + }); + } + + // Get latest quote updates up to 1 minute ago or get updates for a specific symbol without time limit. + // Latest data is always returned in time descending order. + pplx::task quotes_get_latest_data() { + return get_json(web::uri_builder(U("/v1/quotes/latest")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + + if (json_response.is_array()) { + for(size_t i=0; i quotes_get_latest_data(int limit) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(U("latest")).append_query(U("limit"), limit).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + + if (json_response.is_array()) { + for(size_t i=0; i quotes_get_latest_data(std::string symbol) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + + if (json_response.is_array()) { + for(size_t i=0; i quotes_get_latest_data(std::string symbol, int limit) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + + if (json_response.is_array()) { + for(size_t i=0; i quotes_get_historical_data(std::string symbol, const response::precise_time& time_start) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + parse_quotes(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + parse_quotes(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + parse_quotes(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task quotes_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { + utility::string_t url = web::uri_builder(U("/v1/quotes")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::quotes result; + parse_quotes(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get current orderbook snapshot for all symbols + pplx::task orderbooks_get_for_all_symbols() { + return get_json(web::uri_builder(U("/v1/orderbooks/current")).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get current orderbook snapshot for specific symbol + pplx::task orderbooks_get_for_symbol(std::string symbol) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("current")).to_string(); + return get_json(url).then([](web::json::value json_response) -> pplx::task { + response::orderbook result; + parse_orderbook(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get latest orderbook snapshots for a specific symbol, returned in time descending order. + pplx::task orderbooks_get_latest_data(std::string symbol) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("latest")).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task orderbooks_get_latest_data(std::string symbol, int limit) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("latest")).append_query(U("limit"), limit).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + // Get historical orderbook snapshots for a specific symbol within time range, returned in time ascending order. + pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, int limit) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("limit"), limit).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + + pplx::task orderbooks_get_historical_data(std::string symbol, const response::precise_time& time_start, const response::precise_time& time_end, int limit) { + utility::string_t url = web::uri_builder(U("/v1/orderbooks")).append_path(symbol.c_str()).append_path(U("history")).append_query(U("time_start"), iso8601time_to_str(time_start, false)).append_query(U("time_end"), iso8601time_to_str(time_end, false)).append_query(U("limit"), limit).to_string(); + return get_json(web::uri_builder(url).to_string()).then([](web::json::value json_response) -> pplx::task { + response::orderbooks result; + parse_orderbooks(result, json_response); + return pplx::task_from_result(result); + }); + } + }; +} + +#endif + diff --git a/cpp-rest/coin_api_test.cpp b/data-api/cpp-rest/coin_api_test.cpp similarity index 75% rename from cpp-rest/coin_api_test.cpp rename to data-api/cpp-rest/coin_api_test.cpp index 039f79f16d..e16b425e6d 100644 --- a/cpp-rest/coin_api_test.cpp +++ b/data-api/cpp-rest/coin_api_test.cpp @@ -5,8 +5,7 @@ #include "coin_api.h" -#define TEST_KEY "73034021-0EBC-493D-8A00-E0F138111F41" -// 73034021-0EBC-493D-8A00-E0F138111F411 +#define TEST_KEY "YOUR_API_KEY" std::wostream& operator<<(std::wostream& os, const cpp_rest::response::precise_time& pt) { os << pt.year << "/" << pt.month << "/" << pt.day << " "; @@ -180,151 +179,6 @@ std::wostream& operator<<(std::wostream& os, const cpp_rest::response::orderbook return os; } -std::wostream& operator<<(std::wostream& os, const cpp_rest::response::twitter& entry) { - os << " Created at " << entry.created_at.c_str() << std::endl; - os << " ID: " << entry.id << " (" << entry.id_str.c_str() << ")" << std::endl; - os << " Text: " << entry.text.c_str() << std::endl; - os << " Source: " << entry.source.c_str() << std::endl; - if (entry.truncated) - os << " Truncated" << std::endl; - else - os << " Not truncated" << std::endl; - - if (entry.display_text_range.size()) { - os << " Display text range: "; - for(size_t j=0; j + + + + + diff --git a/data-api/csharp-fix-v2/COINAPI.FIX.V2.csproj b/data-api/csharp-fix-v2/COINAPI.FIX.V2.csproj new file mode 100644 index 0000000000..2fe0afc4d6 --- /dev/null +++ b/data-api/csharp-fix-v2/COINAPI.FIX.V2.csproj @@ -0,0 +1,73 @@ + + + + + Debug + AnyCPU + {EE9BC3A5-32F6-4BB7-8751-D80634527705} + Exe + COINAPI.FIX.V2 + csharp_fix + v4.8 + 512 + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + COINAPI.FIX.V2.Program + + + + + + + + + + + + + + + + + + + + Always + + + Always + + + + + Always + + + + + 1.10.0 + + + + \ No newline at end of file diff --git a/data-api/csharp-fix-v2/COINAPI.FIX.V2.sln b/data-api/csharp-fix-v2/COINAPI.FIX.V2.sln new file mode 100644 index 0000000000..dc6cab7238 --- /dev/null +++ b/data-api/csharp-fix-v2/COINAPI.FIX.V2.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29123.88 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "COINAPI.FIX.V2", "COINAPI.FIX.V2.csproj", "{EE9BC3A5-32F6-4BB7-8751-D80634527705}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EE9BC3A5-32F6-4BB7-8751-D80634527705}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6DC7BBDC-2478-4E1D-B9EB-80A2297AB9E1} + EndGlobalSection +EndGlobal diff --git a/csharp-fix/FIX44.xml b/data-api/csharp-fix-v2/FIX44.xml similarity index 100% rename from csharp-fix/FIX44.xml rename to data-api/csharp-fix-v2/FIX44.xml diff --git a/data-api/csharp-fix-v2/MarketDataApp.cs b/data-api/csharp-fix-v2/MarketDataApp.cs new file mode 100644 index 0000000000..1d26508a64 --- /dev/null +++ b/data-api/csharp-fix-v2/MarketDataApp.cs @@ -0,0 +1,486 @@ +using System; +using QuickFix; +using QuickFix.Fields; +using System.Collections.Generic; +using System.Threading; + +namespace COINAPI.FIX.V2 +{ + public class MarketDataApp : QuickFix.MessageCracker, QuickFix.IApplication + { + Session _session = null; + + private bool ExecuteSecurityListRequest = false; + private string FilterBySymbolIdForSecurityListRequest = "^DERIBIT_OPT_(.*)$"; + private string FilterByExchangeNameForSecurityListRequest = "GEMINI"; + + private string DebugSymbol = "COINBASE_SPOT_BTC_USD"; + + private string[] SubscribeBySymbolRegex = new string[] + { + //"^(.*)$" + //"^GEMINI_SPOT_BTC_USD$", // you can use the exact match of the symbol id + //"^GEMINI_SPOT_(.*)_ETH$", // or you can use the regular expression syntax to get eg. all spot symbols to ETH from GEMINI + //"^GEMINI_SPOT_(BCH|LTC)_USD$" // second example of the regex, the BCH/USD & LTC/USD + //"GEMINI_SPOT_ETH_BTC", + //"BINANCEFTS_PERP_BNB_USDT", + //"KRAKEN_SPOT_BTC_GBP", + //"(.*)_SPOT_BTC_USD(.*)$", + //"KRAKEN_SPOT_LTC_BTC", + //"KRAKEN_SPOT_LTC_EUR", + //"BINANCE_SPOT_USDC_TUSD", + //"GEMINI_SPOT_ZEC_ETH", + //"KRAKEN_SPOT_BTC_JPY", + //"BITSTAMP_SPOT_BTC_EUR", + //"BINANCE_SPOT_LTC_USDT", + //"COINBASE_SPOT_BCH_EUR", + //"BYBIT_PERP_ETH_USD", + //"BINANCE_SPOT_LTC_TUSD", + //"BITFINEX_SPOT_BTC_USDT", + //"COINBASE_SPOT_BCH_BTC", + //"COINBASE_SPOT_BTC_EUR", + //"BITMEX_PERP_ETH_USD", + //"BINANCEFTS_PERP_BTC_USDT", + //"KRAKEN_SPOT_ETH_USD", + //"BINANCE_SPOT_BTC_USDC", + //"OKEX_PERP_BTC_USDT", + //"KRAKEN_SPOT_ETH_EUR", + //"BINANCE_SPOT_LTC_PAX", + //"BITMEX_PERP_BTC_USD", + //"BINANCE_SPOT_LTC_BTC", + //"KRAKEN_SPOT_BTC_CAD", + //"BINANCE_SPOT_BTC_TUSD", + //"BINANCE_SPOT_TUSD_USDT", + //"KRAKEN_SPOT_LTC_USD", + //"BITSTAMP_SPOT_BTC_USD", + //"COINBASE_SPOT_BCH_USD", + //"BINANCEFTS_PERP_LTC_USDT", + //"BINANCE_SPOT_ETH_USDT", + //"BINANCE_SPOT_ETH_TUSD", + //"COINBASE_SPOT_BTC_GBP", + //"BINANCEFTS_PERP_BCH_USDT", + //"GEMINI_SPOT_BTC_USD", + //"GEMINI_SPOT_ETH_BTC", + //"KRAKEN_SPOT_BTC_USD", + //"KRAKEN_SPOT_ETH_JPY", + //"KRAKEN_SPOT_USDT_USD", + //"COINBASE_SPOT_ETH_BTC", + //"COINBASE_SPOT_ETH_EUR", + //"BITSTAMP_SPOT_LTC_USD", + //"BITFINEX_SPOT_ETH_USDT", + //"BITFINEX_SPOT_USDT_USD", + //"COINBASE_SPOT_ETH_USD", + //"GEMINI_SPOT_ZEC_USD", + //"KRAKEN_SPOT_ETH_CAD", + //"BINANCE_SPOT_LTC_USDC", + //"BINANCEFTS_PERP_ETC_USDT", + //"GEMINI_SPOT_ZEC_BTC", + //"KRAKEN_SPOT_ETH_GBP", + //"GEMINI_SPOT_ETH_USD", + //"BITFINEX_SPOT_LTC_USD", + //"KRAKEN_SPOT_BTC_EUR", + //"BINANCE_SPOT_ETH_PAX", + //"BINANCE_SPOT_BTC_PAX", + //"COINBASE_SPOT_LTC_USD", + //"BINANCE_SPOT_ETH_USDC", + //"KRAKEN_SPOT_ETH_BTC", + //"BINANCE_SPOT_ETH_BTC", + //"BITFINEX_SPOT_BTC_USD", + //"COINBASE_SPOT_LTC_EUR", + //"BITFINEX_SPOT_ETH_USD", + //"BYBIT_PERP_BTC_USD", + "COINBASE_SPOT_BTC_USD", + //"BITSTAMP_SPOT_ETH_USD", + //"BITFINEX_SPOT_BTC_EUR", + //"BINANCE_SPOT_BTC_USDT", + //"OKEX_PERP_ETH_USDT", + //"BINANCE_SPOT_BTC_USDS", + //"BINANCE_SPOT_LTC_ETH" + //"^(BITSTAMP|GEMINI|COINBASE)_SPOT_BTC_USD$" + }; + + private HashSet _seen = null; + + #region IApplication interface overrides + + public void OnCreate(SessionID sessionID) + { + _session = Session.LookupSession(sessionID); + } + + public void OnLogon(SessionID sessionID) + { + _seen = new HashSet(); + + Console.WriteLine("Logon - " + sessionID.ToString()); + + if (ExecuteSecurityListRequest) + { + // get all the symbols + SecurityListRequestAll(); + + // get symbols only by the symbol prefix + if (!string.IsNullOrWhiteSpace(FilterBySymbolIdForSecurityListRequest)) + { + SecurityListRequestFilteredBySymbolIdPrefix(FilterBySymbolIdForSecurityListRequest); + } + + // get symbols from specific exchange + if (!string.IsNullOrWhiteSpace(FilterByExchangeNameForSecurityListRequest)) + { + SecurityListRequestFilteredByExchange(FilterByExchangeNameForSecurityListRequest); + } + } + + // subscribe by symbol ids + //MarketDataRequestTrades(SubscribeBySymbolRegex); + //MarketDataRequestQuotes(SubscribeBySymbolRegex); + //MarketDataRequestFullOrderbook(SubscribeBySymbolRegex); + MarketDataRequestFullOrderbookIncrementialMsgPerEach(SubscribeBySymbolRegex); + } + + private void MarketDataRequestTrades(string[] symbol_ids) + { + QuickFix.FIX44.MarketDataRequest mdr = new QuickFix.FIX44.MarketDataRequest(); + mdr.MDReqID = new MDReqID(Guid.NewGuid().ToString()); + mdr.SubscriptionRequestType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES); + mdr.MarketDepth = new MarketDepth(0); + + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.TRADE); + mdr.AddGroup(type); + + foreach (var symbol_id in symbol_ids) + { + var relatedsym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + relatedsym.Symbol = new Symbol(symbol_id); + mdr.AddGroup(relatedsym); + } + + SendMessage(mdr); + } + + private void MarketDataRequestQuotes(string[] symbol_ids) + { + QuickFix.FIX44.MarketDataRequest mdr = new QuickFix.FIX44.MarketDataRequest(); + mdr.MDReqID = new MDReqID(Guid.NewGuid().ToString()); + mdr.SubscriptionRequestType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES); + mdr.MarketDepth = new MarketDepth(1); + mdr.MDUpdateType = new MDUpdateType(MDUpdateType.FULL_REFRESH); + + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.BID); + mdr.AddGroup(type); + } + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.OFFER); + mdr.AddGroup(type); + } + + foreach (var symbol_id in symbol_ids) + { + var relatedsym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + relatedsym.Symbol = new Symbol(symbol_id); + mdr.AddGroup(relatedsym); + } + + SendMessage(mdr); + } + + private void MarketDataRequestFullOrderbook(string[] symbol_ids) + { + QuickFix.FIX44.MarketDataRequest mdr = new QuickFix.FIX44.MarketDataRequest(); + mdr.MDReqID = new MDReqID(Guid.NewGuid().ToString()); + mdr.SubscriptionRequestType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES); + mdr.MarketDepth = new MarketDepth(20); + mdr.MDUpdateType = new MDUpdateType(MDUpdateType.FULL_REFRESH); + + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.BID); + mdr.AddGroup(type); + } + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.OFFER); + mdr.AddGroup(type); + } + + foreach (var symbol_id in symbol_ids) + { + var relatedsym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + relatedsym.Symbol = new Symbol(symbol_id); + mdr.AddGroup(relatedsym); + } + + SendMessage(mdr); + } + + private void MarketDataRequestFullOrderbookIncrementialAllInOne(string[] symbol_ids) + { + //Console.WriteLine($"Sending MarketDataRequest with {symbol_ids.Length} items."); + QuickFix.FIX44.MarketDataRequest mdr = new QuickFix.FIX44.MarketDataRequest(); + mdr.MDReqID = new MDReqID(Guid.NewGuid().ToString()); + mdr.SubscriptionRequestType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES); + mdr.MarketDepth = new MarketDepth(0); + mdr.MDUpdateType = new MDUpdateType(MDUpdateType.INCREMENTAL_REFRESH); + + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.BID); + mdr.AddGroup(type); + } + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.OFFER); + mdr.AddGroup(type); + } + + foreach (var symbol_id in symbol_ids) + { + var relatedsym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + relatedsym.Symbol = new Symbol(symbol_id); + mdr.AddGroup(relatedsym); + } + + SendMessage(mdr); + } + + private void MarketDataRequestFullOrderbookIncrementialMsgPerEach(string[] symbol_ids) + { + foreach (var symbol_id in symbol_ids) + { + //Console.WriteLine($"Sending MarketDataRequest with {symbol_ids.Length} items."); + QuickFix.FIX44.MarketDataRequest mdr = new QuickFix.FIX44.MarketDataRequest(); + mdr.MDReqID = new MDReqID(Guid.NewGuid().ToString()); + mdr.SubscriptionRequestType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES); + mdr.MarketDepth = new MarketDepth(0); + mdr.MDUpdateType = new MDUpdateType(MDUpdateType.INCREMENTAL_REFRESH); + + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.BID); + mdr.AddGroup(type); + } + { + var type = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + type.MDEntryType = new MDEntryType(MDEntryType.OFFER); + mdr.AddGroup(type); + } + + var relatedsym = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + relatedsym.Symbol = new Symbol(symbol_id); + mdr.AddGroup(relatedsym); + + SendMessage(mdr); + } + } + + private void SecurityListRequestFilteredBySymbolIdPrefix(string symbol_id_prefix) + { + QuickFix.FIX44.SecurityListRequest slr = + new QuickFix.FIX44.SecurityListRequest( + new SecurityReqID(Guid.NewGuid().ToString()), + new SecurityListRequestType(SecurityListRequestType.SYMBOL)); + slr.Symbol = new Symbol(symbol_id_prefix); + SendMessage(slr); + } + + private void SecurityListRequestFilteredByExchange(string exchange) + { + QuickFix.FIX44.SecurityListRequest slr = + new QuickFix.FIX44.SecurityListRequest( + new SecurityReqID(Guid.NewGuid().ToString()), + new SecurityListRequestType(SecurityListRequestType.SYMBOL)); + slr.SecurityExchange = new SecurityExchange(exchange); + SendMessage(slr); + } + + private void SecurityListRequestAll() + { + QuickFix.FIX44.SecurityListRequest slr = + new QuickFix.FIX44.SecurityListRequest( + new SecurityReqID(Guid.NewGuid().ToString()), + new SecurityListRequestType(SecurityListRequestType.ALL_SECURITIES)); + SendMessage(slr); + } + + public void OnLogout(SessionID sessionID) + { + Console.WriteLine("Logout - " + sessionID.ToString()); + } + + public void FromAdmin(Message message, SessionID sessionID) + { + Console.WriteLine("FromAdmin - " + sessionID.ToString() + " - " + message.ToString()); + } + public void ToAdmin(Message message, SessionID sessionID) + { + Console.WriteLine("ToAdmin - " + sessionID.ToString() + " - " + message.ToString()); + } + + public void FromApp(Message message, SessionID sessionID) + { + //Console.WriteLine("IN: " + message.ToString()); + try + { + Crack(message, sessionID); + } + catch (Exception ex) + { + Console.WriteLine("==Cracker exception=="); + Console.WriteLine(ex.ToString()); + Console.WriteLine(ex.StackTrace); + } + } + + public void ToApp(Message message, SessionID sessionID) + { + //Console.WriteLine("OUT: " + message.ToString()); + } + #endregion + + public void OnMessage(QuickFix.FIX44.SecurityList msg, SessionID s) + { + string text = $"Received SecurityList with id = {msg.SecurityReqID.getValue()}, type {msg.SecurityRequestResult.getValue()}"; + if (msg.IsSetTotNoRelatedSym()) + { + text += $", TotNoRelatedSym = {msg.TotNoRelatedSym.getValue()}, LastFragment = {msg.LastFragment.getValue()}, NoRelatedSym = {msg.NoRelatedSym.getValue()}"; + } + Console.WriteLine(text); + return; + + for (int idx = 0; idx < msg.NoRelatedSym.getValue(); idx++) + { + var symbol = new QuickFix.FIX44.SecurityList.NoRelatedSymGroup(); + msg.GetGroup(idx + 1, symbol); + + Console.WriteLine($"Received symbol {symbol.Symbol} @ {symbol.SecurityExchange}"); + } + Console.WriteLine($"--------------------------------------------------"); + } + + public void OnMessage(QuickFix.FIX44.MarketDataIncrementalRefresh msg, SessionID s) + { + var symbols = new HashSet(); + var entryType = new HashSet(); + + for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + { + var item = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup(); + msg.GetGroup(idx + 1, item); + symbols.Add(item.Symbol.getValue()); + if (MDEntryType.BID == item.MDEntryType.getValue()) + { + entryType.Add("BID"); + } + else if (MDEntryType.OFFER == item.MDEntryType.getValue()) + { + entryType.Add("OFFER"); + } + else if (MDEntryType.TRADE == item.MDEntryType.getValue()) + { + entryType.Add("TRADE"); + } + + if (!_seen.Contains(item.Symbol.getValue()) && MDEntryType.TRADE != item.MDEntryType.getValue()) + { + //throw new Exception("Incremential before snapshot"); + } + } + + for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + { + var item = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup(); + msg.GetGroup(idx + 1, item); + + if (item.Symbol.getValue() == DebugSymbol) + { + Console.WriteLine($"Received MarketDataIncrementalRefresh {msg.NoMDEntries.getValue()} items for {string.Join(",", symbols)} with {string.Join(",", entryType)} (lag: {(DateTime.UtcNow - msg.Header.GetDateTime(52)).TotalMilliseconds} / {(DateTime.UtcNow - item.MDEntryDate.getValue().Add(item.MDEntryTime.getValue().TimeOfDay)).TotalMilliseconds})."); + } + return; + + Console.WriteLine($"{item.MDEntryType} {item.MDUpdateAction} @ {item.Symbol}:"); + if (item.IsSetMDEntryID()) + { + Console.WriteLine($" ID: {item.MDEntryID}"); + } + Console.WriteLine($" Date: {item.MDEntryDate}"); + Console.WriteLine($" Time: {item.MDEntryTime}"); + Console.WriteLine($" Px: {item.MDEntryPx}"); + Console.WriteLine($" Size: {item.MDEntrySize}"); + if (item.IsSetMDEntryOriginator()) + { + Console.WriteLine($" TakerSide: {item.MDEntryOriginator}"); + } + } + Console.WriteLine($"--------------------------------------------------"); + } + + public void OnMessage(QuickFix.FIX44.MarketDataSnapshotFullRefresh msg, SessionID s) + { + _seen.Add(msg.Symbol.getValue()); + + if (msg.Symbol.getValue() == DebugSymbol) + { + for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + { + var item = new QuickFix.FIX44.MarketDataSnapshotFullRefresh.NoMDEntriesGroup(); + msg.GetGroup(idx + 1, item); + Console.WriteLine($"Received MarketDataSnapshotFullRefresh for {msg.Symbol.getValue()} with {msg.NoMDEntries.getValue()} items (lag: {(DateTime.UtcNow - msg.Header.GetDateTime(52)).TotalMilliseconds} / {(DateTime.UtcNow - item.MDEntryDate.getValue().Add(item.MDEntryTime.getValue().TimeOfDay)).TotalMilliseconds})."); + break; + } + } + return; + //for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + //{ + // var level = new QuickFix.FIX44.MarketDataSnapshotFullRefresh.NoMDEntriesGroup(); + // msg.GetGroup(idx + 1, level); + // Console.WriteLine($"{level.MDEntryType} @ {msg.Symbol}:"); + // Console.WriteLine($" Date: {level.MDEntryDate}"); + // Console.WriteLine($" Time: {level.MDEntryTime}"); + // Console.WriteLine($" Px: {level.MDEntryPx}"); + // Console.WriteLine($" Size: {level.MDEntrySize}"); + //} + + Console.WriteLine("BIDS:"); + for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + { + var level = new QuickFix.FIX44.MarketDataSnapshotFullRefresh.NoMDEntriesGroup(); + msg.GetGroup(idx + 1, level); + if (level.MDEntryType.getValue() == MDEntryType.OFFER) + { + continue; + } + Console.WriteLine($"P {level.MDEntryPx} @ S {level.MDEntrySize}"); + } + + Console.WriteLine("ASKS:"); + for (int idx = 0; idx < msg.NoMDEntries.getValue(); idx++) + { + var level = new QuickFix.FIX44.MarketDataSnapshotFullRefresh.NoMDEntriesGroup(); + msg.GetGroup(idx + 1, level); + if (level.MDEntryType.getValue() == MDEntryType.BID) + { + continue; + } + Console.WriteLine($"P {level.MDEntryPx} @ S {level.MDEntrySize}"); + } + } + + private void SendMessage(Message m) + { + if (_session != null) + { + _session.Send(m); + } + else + { + // This probably won't ever happen. + Console.WriteLine("Can't send message: session not created."); + } + } + } +} \ No newline at end of file diff --git a/data-api/csharp-fix-v2/Program.cs b/data-api/csharp-fix-v2/Program.cs new file mode 100644 index 0000000000..0caa5b5bce --- /dev/null +++ b/data-api/csharp-fix-v2/Program.cs @@ -0,0 +1,51 @@ +using QuickFix; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace COINAPI.FIX.V2 +{ + class Program + { + [STAThread] + static void Main(string[] args) + { + try + { + QuickFix.SessionSettings settings = new QuickFix.SessionSettings("config_nossl.cfg"); + MarketDataApp application = new MarketDataApp(); + QuickFix.IMessageStoreFactory storeFactory = new QuickFix.FileStoreFactory(settings); + QuickFix.ILogFactory logFactory = new FileLogFactory(settings); + QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, logFactory); + initiator.Start(); + + System.Threading.Thread.Sleep(Int32.MaxValue); + } + catch (System.Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); + Console.ReadLine(); + } + Environment.Exit(1); + } + + public class NullLogFactory : ILogFactory + { + + #region LogFactory Members + + public NullLogFactory(SessionSettings settings) + { } + + public ILog Create(SessionID sessionID) + { + return new QuickFix.NullLog(); + } + + #endregion + } + } +} diff --git a/csharp-fix/Properties/AssemblyInfo.cs b/data-api/csharp-fix-v2/Properties/AssemblyInfo.cs similarity index 100% rename from csharp-fix/Properties/AssemblyInfo.cs rename to data-api/csharp-fix-v2/Properties/AssemblyInfo.cs diff --git a/data-api/csharp-fix-v2/config_nossl.cfg b/data-api/csharp-fix-v2/config_nossl.cfg new file mode 100644 index 0000000000..160226b40c --- /dev/null +++ b/data-api/csharp-fix-v2/config_nossl.cfg @@ -0,0 +1,31 @@ +[DEFAULT] +ConnectionType=initiator +ReconnectInterval=2 +FileStorePath=store +FileLogPath=log +StartTime=00:00:00 +EndTime=00:00:00 +NonStopSession=Y +UseDataDictionary=Y +ValidateFieldsOutOfOrder=N +DataDictionary=FIX44.xml +#SocketConnectHost=10.230.8.247 +#SocketConnectHost=10.230.8.248 +#SocketConnectHost=dp-ap-northeast-ty-3961.coinapi.net +#SocketConnectHost=dp-eu-west-ld-6096.coinapi.net +SocketConnectHost=dp-us-east-ny.coinapi.net +#SocketConnectHost=dp-us-east-ny-3556.coinapi.net +#SocketConnectHost=fix.coinapi.io +#SocketConnectHost=fix-sandbox.coinapi.io +SocketConnectPort=3302 +#SocketConnectPort=4302 +SSLEnable=N +LogoutTimeout=5 +ResetOnLogon=Y +CheckLatency=N + +[SESSION] +BeginString=FIX.4.4 +SenderCompID=E59434DF-E8E6-4BC2-993B-04FDD5C8D7E8 +TargetCompID=COINAPI_V2 +HeartBtInt=60 diff --git a/data-api/csharp-fix-v2/config_ssl.cfg b/data-api/csharp-fix-v2/config_ssl.cfg new file mode 100644 index 0000000000..14fefed517 --- /dev/null +++ b/data-api/csharp-fix-v2/config_ssl.cfg @@ -0,0 +1,28 @@ +[DEFAULT] +ConnectionType=initiator +ReconnectInterval=2 +FileStorePath=store +FileLogPath=log +StartTime=00:00:00 +EndTime=00:00:00 +NonStopSession=Y +UseDataDictionary=Y +ValidateFieldsOutOfOrder=N +DataDictionary=FIX44.xml +#SocketConnectHost=fix-sandbox.coinapi.io +SocketConnectHost=fix.coinapi.io +SocketConnectPort=3303 +SSLEnable=Y +#SSLServerName=fix-sandbox.coinapi.io +SSLServerName=fix.coinapi.io +SSLValidateCertificates=Y +SSLCheckCertificateRevocation=Y +LogoutTimeout=5 +ResetOnLogon=Y + +[SESSION] +BeginString=FIX.4.4 +#SenderCompID=761B188E-FC7E-4E72-BC42-3AD7D23CCE75 +SenderCompID=5F8C7105-B96C-494F-8D01-54D31CB86431 +TargetCompID=COINAPI_V2 +HeartBtInt=10 diff --git a/data-api/csharp-rest/.gitignore b/data-api/csharp-rest/.gitignore new file mode 100644 index 0000000000..62e4e8f2e1 --- /dev/null +++ b/data-api/csharp-rest/.gitignore @@ -0,0 +1,352 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/data-api/csharp-rest/CoinAPI.REST.V1.Example/CoinAPI.REST.V1.Example.csproj b/data-api/csharp-rest/CoinAPI.REST.V1.Example/CoinAPI.REST.V1.Example.csproj new file mode 100644 index 0000000000..e8f077ad1c --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1.Example/CoinAPI.REST.V1.Example.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp3.1 + + + + + + + diff --git a/data-api/csharp-rest/CoinAPI.REST.V1.Example/Program.cs b/data-api/csharp-rest/CoinAPI.REST.V1.Example/Program.cs new file mode 100644 index 0000000000..d34e36ba83 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1.Example/Program.cs @@ -0,0 +1,683 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CoinAPI.REST.V1; + +namespace CoinAPI.REST.V1.Example +{ + class Program + { + static void Main(string[] args) + { + var coinApiEndpointTester = new CoinApiRestEndpointsTester("4FAB4B58-9D8F-4CFF-9FB3-83833109584E") + { + Log = s => Console.WriteLine(s) + }; + + Console.WriteLine("Assets with icons"); + var assetsIcons = coinApiEndpointTester.Metadata_list_assets_iconsAsync(32).GetAwaiter().GetResult(); + foreach (var assetIcon in assetsIcons.Data) + { + Console.WriteLine($"asset id = {assetIcon.asset_id} iconUrl = {assetIcon.url}"); + } + + Console.WriteLine("Exchanges with icons"); + var exhcangesIcons = coinApiEndpointTester.Metadata_list_exchanges_iconsAsync(32).GetAwaiter().GetResult(); + foreach (var exchaingeIcon in exhcangesIcons.Data) + { + Console.WriteLine($"exchange id = {exchaingeIcon.exchange_id} iconUrl = {exchaingeIcon.url}"); + } + + Console.Write("Exchange:"); + Console.Write(Environment.NewLine); + var exchange = coinApiEndpointTester.Metadata_list_exchangesAsync().GetAwaiter().GetResult(); + foreach (var item in exchange.Data) + { + Console.Write("exchange_id:" + item.exchange_id); + Console.Write(Environment.NewLine); + Console.Write("website:" + item.website); + Console.Write(Environment.NewLine); + Console.Write("name:" + item.name); + Console.Write(Environment.NewLine); + Console.WriteLine("volume_1day_usd:" + item.volume_1day_usd); + Console.WriteLine("volume_1hrs_usd:" + item.volume_1hrs_usd); + Console.WriteLine("volume_1mth_usd:" + item.volume_1mth_usd); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + //Console.Write("symbols:"); + //Console.Write(Environment.NewLine); + //var symbols = coinApi.Metadata_list_symbols(); + //foreach (var item in symbols) + //{ + // Console.Write("symbol_id:" + item.symbol_id); + // Console.Write(Environment.NewLine); + // Console.Write("exchange_id:" + item.exchange_id); + // Console.Write(Environment.NewLine); + // Console.Write("symbol_type:" + item.symbol_type); + // Console.Write(Environment.NewLine); + + // if (item.symbol_type == "OPTION") + // { + // Console.Write("option_type_is_call:" + item.option_type_is_call); + // Console.Write(Environment.NewLine); + // Console.Write("option_strike_price:" + item.option_strike_price); + // Console.Write(Environment.NewLine); + // Console.Write("option_contract_unit:" + item.option_contract_unit); + // Console.Write(Environment.NewLine); + // Console.Write("option_exercise_style:" + item.option_exercise_style); + // Console.Write(Environment.NewLine); + // Console.Write("option_expiration_time:" + item.option_expiration_time); + // Console.Write(Environment.NewLine); + // } + + // if (item.symbol_type == "FUTURES") + // { + // Console.Write("future_delivery_time:" + item.future_delivery_time); + // Console.Write(Environment.NewLine); + // } + + // Console.Write("asset_id_base:" + item.asset_id_base); + // Console.Write(Environment.NewLine); + // Console.Write("asset_id_quote:" + item.asset_id_quote); + // Console.Write(Environment.NewLine); + // Console.WriteLine("volume_1day_usd:" + item.volume_1day_usd); + // Console.WriteLine("volume_1hrs_usd:" + item.volume_1hrs_usd); + // Console.WriteLine("volume_1mth_usd:" + item.volume_1mth_usd); + // Console.WriteLine("volume_1day:" + item.volume_1day); + // Console.WriteLine("volume_1hrs:" + item.volume_1hrs); + // Console.WriteLine("volume_1mth:" + item.volume_1mth); + // Console.WriteLine("price:" + item.price); + // Console.Write("--------------------------------------------------------------------------------------------------------"); + // Console.Write(Environment.NewLine); + //} + + //Console.WriteLine($"Symbols mapping for BCEX: "); + //var mappingsList = coinApi.Metadata_symbol_mapping("BCEX"); + + //foreach (var mapping in mappingsList) + //{ + // Console.WriteLine($"symbol_id_exchange: {mapping.symbol_id_exchange}"); + // Console.WriteLine($"price_precision: {mapping.price_precision}"); + // Console.WriteLine($"size_precision: {mapping.size_precision}"); + //} + + Console.Write("Asset:"); + Console.Write(Environment.NewLine); + var assets = coinApiEndpointTester.Metadata_list_assetsAsync().GetAwaiter().GetResult(); + foreach (var item in assets.Data) + { + Console.Write("asset_id:" + item.asset_id); + Console.Write(Environment.NewLine); + Console.Write("name:" + item.name); + Console.Write(Environment.NewLine); + Console.Write("type_is_crypto:" + item.type_is_crypto); + Console.Write(Environment.NewLine); + Console.WriteLine("volume_1day_usd:" + item.volume_1day_usd); + Console.WriteLine("volume_1hrs_usd:" + item.volume_1hrs_usd); + Console.WriteLine("volume_1mth_usd:" + item.volume_1mth_usd); + Console.WriteLine("price_usd:" + item.price_usd); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Exchangerate:"); + Console.Write(Environment.NewLine); + var exchange_rate = coinApiEndpointTester.Exchange_rates_get_specific_rateAsync("BTC", "USD").GetAwaiter().GetResult(); + + Console.Write("time:" + exchange_rate.Data.time); + Console.Write(Environment.NewLine); + Console.Write("asset_id_base:" + exchange_rate.Data.asset_id_base); + Console.Write(Environment.NewLine); + Console.Write("asset_id_quote:" + exchange_rate.Data.asset_id_quote); + Console.Write(Environment.NewLine); + Console.Write("rate:" + exchange_rate.Data.rate); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + + Console.Write("Exchangerate Last Week:"); + Console.Write(Environment.NewLine); + var lastweek = DateTime.Now.AddDays(-7); + var exchange_rate_last_week = coinApiEndpointTester.Exchange_rates_get_specific_rateAsync("BTC", "USD", lastweek).GetAwaiter().GetResult().Data; + + Console.Write("time:" + exchange_rate_last_week.time); + Console.Write(Environment.NewLine); + Console.Write("asset_id_base:" + exchange_rate_last_week.asset_id_base); + Console.Write(Environment.NewLine); + Console.Write("asset_id_quote:" + exchange_rate_last_week.asset_id_quote); + Console.Write(Environment.NewLine); + Console.Write("rate:" + exchange_rate_last_week.rate); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + + Console.Write("Exchangerate current rates:"); + Console.Write(Environment.NewLine); + var current_rates = coinApiEndpointTester.Exchange_rates_get_all_current_ratesAsync("BTC").GetAwaiter().GetResult().Data; + + Console.Write("Asset ID Base:" + current_rates.asset_id_base); + Console.Write(Environment.NewLine); + foreach (var item in current_rates.rates) + { + Console.Write("time:" + item.time); + Console.Write(Environment.NewLine); + Console.Write("asset_id_quote:" + item.asset_id_quote); + Console.Write(Environment.NewLine); + Console.Write("rate:" + item.rate); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Ohlcv list all periods:"); + Console.Write(Environment.NewLine); + var periods = coinApiEndpointTester.Ohlcv_list_all_periodsAsync().GetAwaiter().GetResult().Data; + foreach (var item in periods) + { + Console.Write("period_id:" + item.period_id); + Console.Write(Environment.NewLine); + Console.Write("length_seconds:" + item.length_seconds); + Console.Write(Environment.NewLine); + Console.Write("length_months:" + item.length_months); + Console.Write(Environment.NewLine); + Console.Write("unit_count:" + item.unit_count); + Console.Write(Environment.NewLine); + Console.Write("unit_name:" + item.unit_name); + Console.Write(Environment.NewLine); + Console.Write("display_name:" + item.display_name); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + var symbolId = "BITSTAMP_SPOT_BTC_USD"; + Console.Write("Ohlcv latest data:"); + Console.Write(Environment.NewLine); + var ohlcv_latest = coinApiEndpointTester.Ohlcv_latest_dataAsync(symbolId, "1MIN").GetAwaiter().GetResult().Data; + foreach (var item in ohlcv_latest) + { + Console.Write("time_period_start:" + item.time_period_start); + Console.Write(Environment.NewLine); + Console.Write("time_period_end:" + item.time_period_end); + Console.Write(Environment.NewLine); + Console.Write("time_open:" + item.time_open); + Console.Write(Environment.NewLine); + Console.Write("time_close:" + item.time_close); + Console.Write(Environment.NewLine); + Console.Write("price_open:" + item.price_open); + Console.Write(Environment.NewLine); + Console.Write("price_high:" + item.price_high); + Console.Write(Environment.NewLine); + Console.Write("price_low:" + item.price_low); + Console.Write(Environment.NewLine); + Console.Write("price_close:" + item.price_close); + Console.Write(Environment.NewLine); + Console.Write("volume_traded:" + item.volume_traded); + Console.Write(Environment.NewLine); + Console.Write("trades_count:" + item.trades_count); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Ohlcv last year:"); + Console.Write(Environment.NewLine); + var start_of_2016 = new DateTime(2016, 1, 1); + var ohlcv_historical = coinApiEndpointTester.Ohlcv_historical_dataAsync(symbolId, "1MIN", start_of_2016).GetAwaiter().GetResult().Data; + foreach (var item in ohlcv_historical) + { + Console.Write("time_period_start:" + item.time_period_start); + Console.Write(Environment.NewLine); + Console.Write("time_period_end:" + item.time_period_end); + Console.Write(Environment.NewLine); + Console.Write("time_open:" + item.time_open); + Console.Write(Environment.NewLine); + Console.Write("time_close:" + item.time_close); + Console.Write(Environment.NewLine); + Console.Write("price_open:" + item.price_open); + Console.Write(Environment.NewLine); + Console.Write("price_high:" + item.price_high); + Console.Write(Environment.NewLine); + Console.Write("price_low:" + item.price_low); + Console.Write(Environment.NewLine); + Console.Write("price_close:" + item.price_close); + Console.Write(Environment.NewLine); + Console.Write("volume_traded:" + item.volume_traded); + Console.Write(Environment.NewLine); + Console.Write("trades_count:" + item.trades_count); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Trades latest data all:"); + Console.Write(Environment.NewLine); + var latest_trades = coinApiEndpointTester.Trades_latest_data_allAsync().GetAwaiter().GetResult().Data; + + foreach (var item in latest_trades) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("uuid:" + item.uuid); + Console.Write(Environment.NewLine); + Console.Write("price:" + item.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + item.size); + Console.Write(Environment.NewLine); + Console.Write("taker_side:" + item.taker_side); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Trades latest data symbol:"); + Console.Write(Environment.NewLine); + var latest_trades_doge = coinApiEndpointTester.Trades_latest_data_symbolAsync(symbolId).GetAwaiter().GetResult().Data; + foreach (var item in latest_trades_doge) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("uuid:" + item.uuid); + Console.Write(Environment.NewLine); + Console.Write("price:" + item.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + item.size); + Console.Write(Environment.NewLine); + Console.Write("taker_side:" + item.taker_side); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Trades historical data:"); + Console.Write(Environment.NewLine); + var historical_trades_btc = coinApiEndpointTester.Trades_historical_dataAsync(symbolId, start_of_2016).GetAwaiter().GetResult().Data; + foreach (var item in historical_trades_btc) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("uuid:" + item.uuid); + Console.Write(Environment.NewLine); + Console.Write("price:" + item.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + item.size); + Console.Write(Environment.NewLine); + Console.Write("taker_side:" + item.taker_side); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + Console.Write("Quotes current data all:"); + Console.Write(Environment.NewLine); + var current_quotes = coinApiEndpointTester.Quotes_current_data_allAsync().GetAwaiter().GetResult().Data; + foreach (var item in current_quotes) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("ask_price:" + item.ask_price); + Console.Write(Environment.NewLine); + Console.Write("ask_size:" + item.ask_size); + Console.Write(Environment.NewLine); + Console.Write("bid_price:" + item.bid_price); + Console.Write(Environment.NewLine); + Console.Write("bid_size:" + item.bid_size); + Console.Write(Environment.NewLine); + //Console.Write("last_trade:" + item.last_trade); + //Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + Console.Write("Quotes current data symbol:"); + Console.Write(Environment.NewLine); + var current_quote_btc_usd = coinApiEndpointTester.Quotes_current_data_symbolAsync(symbolId).GetAwaiter().GetResult().Data; + + Console.Write("symbol_id:" + current_quote_btc_usd.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + current_quote_btc_usd.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + current_quote_btc_usd.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("ask_price:" + current_quote_btc_usd.ask_price); + Console.Write(Environment.NewLine); + Console.Write("ask_size:" + current_quote_btc_usd.ask_size); + Console.Write(Environment.NewLine); + Console.Write("bid_price:" + current_quote_btc_usd.bid_price); + Console.Write(Environment.NewLine); + Console.Write("bid_size:" + current_quote_btc_usd.bid_size); + Console.Write(Environment.NewLine); + if (current_quote_btc_usd.last_trade != null) + { + Console.Write("last trade:"); + Console.Write(Environment.NewLine); + Console.Write("symbol_id:" + current_quote_btc_usd.last_trade.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + current_quote_btc_usd.last_trade.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + current_quote_btc_usd.last_trade.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("uuid:" + current_quote_btc_usd.last_trade.uuid); + Console.Write(Environment.NewLine); + Console.Write("price:" + current_quote_btc_usd.last_trade.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + current_quote_btc_usd.last_trade.size); + Console.Write(Environment.NewLine); + Console.Write("taker_side:" + current_quote_btc_usd.last_trade.taker_side); + Console.Write(Environment.NewLine); + } + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + + Console.Write("Quotes latest data all:"); + Console.Write(Environment.NewLine); + var quotes_latest_data = coinApiEndpointTester.Quotes_latest_data_allAsync().GetAwaiter().GetResult().Data; + foreach (var item in quotes_latest_data) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("ask_price:" + item.ask_price); + Console.Write(Environment.NewLine); + Console.Write("ask_size:" + item.ask_size); + Console.Write(Environment.NewLine); + Console.Write("bid_price:" + item.bid_price); + Console.Write(Environment.NewLine); + Console.Write("bid_size:" + item.bid_size); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + Console.Write("Quotes latest data symbol:"); + Console.Write(Environment.NewLine); + var quotes_latest_data_btc_usd = coinApiEndpointTester.Quotes_latest_data_symbolAsync(symbolId).GetAwaiter().GetResult().Data; + foreach (var item in quotes_latest_data_btc_usd) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("ask_price:" + item.ask_price); + Console.Write(Environment.NewLine); + Console.Write("ask_size:" + item.ask_size); + Console.Write(Environment.NewLine); + Console.Write("bid_price:" + item.bid_price); + Console.Write(Environment.NewLine); + Console.Write("bid_size:" + item.bid_size); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + Console.Write("Quotes historical data:"); + Console.Write(Environment.NewLine); + var quotes_historical_data_btc_usd = coinApiEndpointTester.Quotes_historical_dataAsync(symbolId, start_of_2016).GetAwaiter().GetResult().Data; + foreach (var item in quotes_historical_data_btc_usd) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + Console.Write("ask_price:" + item.ask_price); + Console.Write(Environment.NewLine); + Console.Write("ask_size:" + item.ask_size); + Console.Write(Environment.NewLine); + Console.Write("bid_price:" + item.bid_price); + Console.Write(Environment.NewLine); + Console.Write("bid_size:" + item.bid_size); + Console.Write(Environment.NewLine); + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + Console.Write("Orderbooks current data all:"); + Console.Write(Environment.NewLine); + var orderbooks_current_data = coinApiEndpointTester.Orderbooks_current_data_all_filtered_bitstampAsync().GetAwaiter().GetResult().Data; + foreach (var item in orderbooks_current_data) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.asks) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.bids) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Orderbooks current data symbol:"); + Console.Write(Environment.NewLine); + var orderbooks_current_data_btc_usd = coinApiEndpointTester.Orderbooks_current_data_symbolAsync(symbolId).GetAwaiter().GetResult().Data; + Console.Write("symbol_id:" + orderbooks_current_data_btc_usd.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + orderbooks_current_data_btc_usd.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + orderbooks_current_data_btc_usd.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in orderbooks_current_data_btc_usd.asks) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in orderbooks_current_data_btc_usd.bids) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + + Console.Write("Orderbooks last data:"); + Console.Write(Environment.NewLine); + var orderbooks_latest_data_btc_usd = coinApiEndpointTester.Orderbooks_last_dataAsync(symbolId).GetAwaiter().GetResult().Data; + foreach (var item in orderbooks_latest_data_btc_usd) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.asks) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.bids) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Orderbooks historical data:"); + Console.Write(Environment.NewLine); + var orderbooks_historical_data_btc_usd = coinApiEndpointTester.Orderbooks_historical_dataAsync(symbolId, start_of_2016).GetAwaiter().GetResult().Data; + foreach (var item in orderbooks_historical_data_btc_usd) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.asks) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.bids) + { + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Orderbooks level 3 current data all:"); + Console.Write(Environment.NewLine); + var orderbooks3_current_data = coinApiEndpointTester.Orderbooks3_current_data_all_filtered_bitstampAsync().GetAwaiter().GetResult().Data; + foreach (var item in orderbooks3_current_data) + { + Console.Write("symbol_id:" + item.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + item.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + item.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.asks) + { + Console.Write("id:" + itm.id); + Console.Write(Environment.NewLine); + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in item.bids) + { + Console.Write("id:" + itm.id); + Console.Write(Environment.NewLine); + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + } + + Console.Write("Orderbooks level 3 current data symbol:"); + Console.Write(Environment.NewLine); + var orderbooks3_current_data_btc_usd = coinApiEndpointTester.Orderbooks3_current_data_symbolAsync("BITSTAMP_SPOT_BTC_USD").GetAwaiter().GetResult().Data; + Console.Write("symbol_id:" + orderbooks3_current_data_btc_usd.symbol_id); + Console.Write(Environment.NewLine); + Console.Write("time_exchange:" + orderbooks3_current_data_btc_usd.time_exchange); + Console.Write(Environment.NewLine); + Console.Write("time_coinapi:" + orderbooks3_current_data_btc_usd.time_coinapi); + Console.Write(Environment.NewLine); + + Console.Write("Asks:"); + Console.Write(Environment.NewLine); + foreach (var itm in orderbooks3_current_data_btc_usd.asks) + { + Console.Write("id:" + itm.id); + Console.Write(Environment.NewLine); + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + + } + Console.Write("Bids:"); + Console.Write(Environment.NewLine); + foreach (var itm in orderbooks3_current_data_btc_usd.bids) + { + Console.Write("id:" + itm.id); + Console.Write(Environment.NewLine); + Console.Write("price:" + itm.price); + Console.Write(Environment.NewLine); + Console.Write("size:" + itm.size); + Console.Write(Environment.NewLine); + } + + Console.Write("--------------------------------------------------------------------------------------------------------"); + Console.Write(Environment.NewLine); + + + Console.WriteLine("=== END ==="); + Console.ReadLine(); + } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1.Tests/CoinAPI.REST.V1.Tests.csproj b/data-api/csharp-rest/CoinAPI.REST.V1.Tests/CoinAPI.REST.V1.Tests.csproj new file mode 100644 index 0000000000..8ae4c5b9e4 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1.Tests/CoinAPI.REST.V1.Tests.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp3.0 + + false + + + + + + + + + + diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/CoinAPI.REST.V1.csproj b/data-api/csharp-rest/CoinAPI.REST.V1/CoinAPI.REST.V1.csproj new file mode 100644 index 0000000000..10aeb2e2bd --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/CoinAPI.REST.V1.csproj @@ -0,0 +1,35 @@ + + + + netstandard1.1 + true + CoinAPI.REST.V1 + COINAPI LTD + CoinAPI.REST + SDK for www.CoinAPI.io REST API + https://www.CoinAPI.io + https://www.coinapi.io/img/favicon.png + https://github.com/coinapi/coinapi-sdk/ + GitHub.com + coinapi sdk rest v1 api + en + LICENSE + COINAPI LTD + COINAPI LTD or its affiliates + 2.0.9 + 17704ec2-7050-452e-99b5-0eddf76dea5d + + + + + + + + + + True + + + + + diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiCheckStatusCode.cs b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiCheckStatusCode.cs new file mode 100644 index 0000000000..b4eb8d766a --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiCheckStatusCode.cs @@ -0,0 +1,9 @@ +namespace CoinAPI.REST.V1 +{ + public enum CoinApiCheckStatusCode + { + GoodResponse = 1, + BadData = 2, + ExceptionThrown = 3 + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiEndpointUrls.cs b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiEndpointUrls.cs new file mode 100644 index 0000000000..682a9c6e03 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiEndpointUrls.cs @@ -0,0 +1,52 @@ +namespace CoinAPI.REST.V1 +{ + public static class CoinApiEndpointUrls + { + public static string Exchanges() => "/v1/exchanges"; + public static string Assets() => "/v1/assets"; + public static string Symbols() => "/v1/symbols"; + public static string Symbols(string exchangeId) => $"/v1/symbols/{exchangeId}"; + public static string Assests_Icons(int iconSize) => $"/v1/assets/icons/{iconSize}"; + public static string Exchanges_Icons(int iconSize) => $"/v1/exchanges/icons/{iconSize}"; + public static string ExchangeRateSpecific(string baseId, string quoteId, string time) => string.Format("/v1/exchangerate/{0}/{1}?time={2}", baseId, quoteId, time); + public static string ExchangeRateSpecific(string baseId, string quoteId) => string.Format("/v1/exchangerate/{0}/{1}", baseId, quoteId); + public static string ExchangeRate(string baseId, bool invert) => string.Format("/v1/exchangerate/{0}?invert={1}", baseId, invert); + public static string Ohlcv_Periods() => "/v1/ohlcv/periods"; + public static string Ohlcv_LatestData(string symbolId, string periodId, int limit) => string.Format("/v1/ohlcv/{0}/latest?period_id={1}&limit={2}", symbolId, periodId, limit); + public static string Ohlcv_LatestData(string symbolId, string periodId) => string.Format("/v1/ohlcv/{0}/latest?period_id={1}", symbolId, periodId); + public static string Ohlcv_Asset_Latest(string assetBase, string assetQuote, string periodId) => string.Format("/v1/ohlcv/{0}/{1}/latest?period_id={2}", assetBase, assetQuote, periodId); + public static string Ohlcv_HistoricalData(string symbolId, string periodId, string start, string end, int limit) => string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&time_end={3}&limit={4}", symbolId, periodId, start, end, limit); + public static string Ohlcv_HistoricalData(string symbolId, string periodId, string start, string end) => string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&time_end={3}", symbolId, periodId, start, end); + public static string Ohlcv_HistoricalData(string symbolId, string periodId, string start, int limit) => string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}&limit={3}", symbolId, periodId, start, limit); + public static string Ohlcv_HistoricalData(string symbolId, string periodId, string start) => string.Format("/v1/ohlcv/{0}/history?period_id={1}&time_start={2}", symbolId, periodId, start); + public static string Trades_Latest() => "/v1/trades/latest"; + public static string Trades_Latest(int limit) => string.Format("/v1/trades/latest?limit={0}", limit); + public static string Trades_LatestSymbol(string symbolId) => string.Format("/v1/trades/{0}/latest", symbolId); + public static string Trades_LatestSymbol(string symbolId, int limit) => string.Format("/v1/trades/{0}/latest?limit={1}", symbolId, limit); + public static string Trades_HistoricalData(string symbolId, string start, string end, int limit) => string.Format("/v1/trades/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start, end, limit); + public static string Trades_HistoricalData(string symbolId, string start) => string.Format("/v1/trades/{0}/history?time_start={1}", symbolId, start); + public static string Trades_HistoricalData(string symbolId, string start, string end) => string.Format("/v1/trades/{0}/history?time_start={1}&time_end={2}", symbolId, start, end); + public static string Trades_HistoricalData(string symbolId, string start, int limit) => string.Format("/v1/trades/{0}/history?time_start={1}&limit={2}", symbolId, start, limit); + public static string Quotes_Current() => "/v1/quotes/current"; + public static string Quotes_CurrentSymbol(string symbolId) => string.Format("/v1/quotes/{0}/current", symbolId); + public static string Quotes_Latest() => "/v1/quotes/latest"; + public static string Quotes_Latest(int limit) => string.Format("/v1/quotes/latest?limit={0}", limit); + public static string Quotes_LatestSymbol(string symbolId) => string.Format("/v1/quotes/{0}/latest", symbolId); + public static string Quotes_LatestSymbol(string symbolId, int limit) => string.Format("/v1/quotes/{0}/latest?limit={1}", symbolId, limit); + public static string Quotes_HistoricalData(string symbolId, string start, string end, int limit) => string.Format("/v1/quotes/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start, end, limit); + public static string Quotes_HistoricalData(string symbolId, string start) => string.Format("/v1/quotes/{0}/history?time_start={1}", symbolId, start); + public static string Quotes_HistoricalData(string symbolId, string start, string end) => string.Format("/v1/quotes/{0}/history?time_start={1}&time_end={2}", symbolId, start, end); + public static string Quotes_HistoricalData(string symbolId, string start, int limit) => string.Format("/v1/quotes/{0}/history?time_start={1}&limit={2}", symbolId, start, limit); + public static string Orderbooks_CurrentFilteredBitstamp() => "/v1/orderbooks/current?filter_symbol_id=BITSTAMP"; + public static string Orderbooks_CurrentSymbol(string symbolId) => string.Format("/v1/orderbooks/{0}/current", symbolId); + public static string Orderbooks_LatestData(string symbolId, int limit) => string.Format("/v1/orderbooks/{0}/latest?limit={1}", symbolId, limit); + public static string Orderbooks_LatestData(string symbolId) => string.Format("/v1/orderbooks/{0}/latest", symbolId); + public static string Orderbooks_HistoricalData(string symbolId, string start, string end, int limit) => string.Format("/v1/orderbooks/{0}/history?time_start={1}&time_end={2}&limit={3}", symbolId, start, end, limit); + public static string Orderbooks_HistoricalData(string symbolId, string start) => string.Format("/v1/orderbooks/{0}/history?time_start={1}", symbolId, start); + public static string Orderbooks_HistoricalData(string symbolId, string start, string end) => string.Format("/v1/orderbooks/{0}/history?time_start={1}&time_end={2}", symbolId, start, end); + public static string Orderbooks_HistoricalData(string symbolId, string start, int limit) => string.Format("/v1/orderbooks/{0}/history?time_start={1}&limit={2}", symbolId, start, limit); + public static string Orderbooks3_CurrentFilteredBitstamp() => "/v1/orderbooks3/current?filter_symbol_id=BITSTAMP"; + public static string Orderbooks3_Current(string symbolId) => string.Format("/v1/orderbooks3/{0}/current", symbolId); + } + +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestClient.cs b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestClient.cs new file mode 100644 index 0000000000..473dc63ac7 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestClient.cs @@ -0,0 +1,327 @@ + +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using CoinAPI.REST.V1.Exceptions; +using CoinAPI.REST.V1.DataModels; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 +{ + public class CoinApiRestClient + { + private string apikey; + public string DateFormat => "yyyy-MM-ddTHH:mm:ss.fff"; + private string WebUrl = "https://rest.coinapi.io"; + + public CoinApiRestClient(string apikey, bool sandbox = false) + { + this.apikey = apikey; + if (sandbox) + { + WebUrl = "https://rest-sandbox.coinapi.io"; + } + this.WebUrl = WebUrl.TrimEnd('/'); + } + + public CoinApiRestClient(string apikey, string url) + { + this.apikey = apikey; + this.WebUrl = url.TrimEnd('/'); + } + + private async Task GetData(string url) + { + try + { + using (var handler = new HttpClientHandler()) + { + handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; + using (var client = new HttpClient(handler, false)) + { + client.DefaultRequestHeaders.Add("X-CoinAPI-Key", apikey); + + HttpResponseMessage response = await client.GetAsync(WebUrl + url).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + await RaiseError(response).ConfigureAwait(false); + + return await Deserialize(response).ConfigureAwait(false); + } + } + } + catch (CoinApiException) + { + throw; + } + catch (Exception e) + { + throw new CoinApiException("Unexpected error", e); + } + } + + private static async Task RaiseError(HttpResponseMessage response) + { + var message = (await Deserialize(response).ConfigureAwait(false)).message; + + switch ((int)response.StatusCode) + { + case 400: + throw new BadRequestException(message); + case 401: + throw new UnauthorizedException(message); + case 403: + throw new ForbiddenException(message); + case 429: + throw new TooManyRequestsException(message); + case 550: + throw new NoDataException(message); + default: + throw new CoinApiException(message); + } + } + + private static async Task Deserialize(HttpResponseMessage responseMessage) + { + var responseString = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); + var data = JsonConvert.DeserializeObject(responseString); + return data; + } + + public Task> Metadata_list_exchangesAsync() + { + return GetData>(CoinApiEndpointUrls.Exchanges()); + } + + public Task> Metadata_list_assetsAsync() + { + return GetData>(CoinApiEndpointUrls.Assets()); + } + + public Task> Metadata_list_symbolsAsync() + { + return GetData>(CoinApiEndpointUrls.Symbols()); + } + + public Task> Metadata_list_symbols_exchangeAsync(string exchangeId) + { + return GetData>(CoinApiEndpointUrls.Symbols(exchangeId)); + } + + public Task> Metadata_list_assets_iconsAsync(int iconSize) + { + return GetData>(CoinApiEndpointUrls.Assests_Icons(iconSize)); + } + + public Task> Metadata_list_exchanges_iconsAsync(int iconSize) + { + return GetData>(CoinApiEndpointUrls.Exchanges_Icons(iconSize)); + } + public Task Exchange_rates_get_specific_rateAsync(string baseId, string quoteId, DateTime time) + { + var url = CoinApiEndpointUrls.ExchangeRateSpecific(baseId, quoteId, time.ToString(DateFormat)); + return GetData(url); + } + public Task Exchange_rates_get_specific_rateAsync(string baseId, string quoteId) + { + var url = CoinApiEndpointUrls.ExchangeRateSpecific(baseId, quoteId); + return GetData(url); + } + + public Task Exchange_rates_get_all_current_ratesAsync(string baseId, bool invert = false) + { + var url = CoinApiEndpointUrls.ExchangeRate(baseId, invert); + return GetData(url); + } + + public Task> Ohlcv_list_all_periodsAsync() + { + var url = CoinApiEndpointUrls.Ohlcv_Periods(); + return GetData>(url); + } + + + public Task> Ohlcv_latest_dataAsync(string symbolId, string periodId, int limit) + { + var url = CoinApiEndpointUrls.Ohlcv_LatestData(symbolId, periodId, limit); + return GetData>(url); + } + public Task> Ohlcv_latest_dataAsync(string symbolId, string periodId) + { + var url = CoinApiEndpointUrls.Ohlcv_LatestData(symbolId, periodId); + return GetData>(url); + } + + public Task> Ohlcv_latest_asset_dataAsync(string assetBase, string assetQuote, string periodId) + { + var url = CoinApiEndpointUrls.Ohlcv_Asset_Latest(assetBase, assetQuote, periodId); + return GetData>(url); + } + + public Task> Ohlcv_historical_dataAsync(string symbolId, string periodId, DateTime start, DateTime end, int limit) + { + var url = CoinApiEndpointUrls.Ohlcv_HistoricalData(symbolId, periodId, start.ToString(DateFormat), end.ToString(DateFormat), limit); + return GetData>(url); + } + public Task> Ohlcv_historical_dataAsync(string symbolId, string periodId, DateTime start, DateTime end) + { + var url = CoinApiEndpointUrls.Ohlcv_HistoricalData(symbolId, periodId, start.ToString(DateFormat), end.ToString(DateFormat)); + return GetData>(url); + } + public Task> Ohlcv_historical_dataAsync(string symbolId, string periodId, DateTime start, int limit) + { + var url = CoinApiEndpointUrls.Ohlcv_HistoricalData(symbolId, periodId, start.ToString(DateFormat), limit); + return GetData>(url); + } + public Task> Ohlcv_historical_dataAsync(string symbolId, string periodId, DateTime start) + { + var url = CoinApiEndpointUrls.Ohlcv_HistoricalData(symbolId, periodId, start.ToString(DateFormat)); + return GetData>(url); + } + + public Task> Trades_latest_data_allAsync() + { + var url = CoinApiEndpointUrls.Trades_Latest(); + return GetData>(url); + } + public Task> Trades_latest_data_allAsync(int limit) + { + var url = CoinApiEndpointUrls.Trades_Latest(limit); + return GetData>(url); + } + + + public Task> Trades_latest_data_symbolAsync(string symbolId) + { + var url = CoinApiEndpointUrls.Trades_LatestSymbol(symbolId); + return GetData>(url); + } + public Task> Trades_latest_data_symbolAsync(string symbolId, int limit) + { + var url = CoinApiEndpointUrls.Trades_LatestSymbol(symbolId, limit); + return GetData>(url); + } + + public Task> Trades_historical_dataAsync(string symbolId, DateTime start, DateTime end, int limit) + { + + return GetData>(CoinApiEndpointUrls.Trades_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat), limit)); + } + public Task> Trades_historical_dataAsync(string symbolId, DateTime start) + { + return GetData>(CoinApiEndpointUrls.Trades_HistoricalData(symbolId, start.ToString(DateFormat))); + } + public Task> Trades_historical_dataAsync(string symbolId, DateTime start, DateTime end) + { + + return GetData>(CoinApiEndpointUrls.Trades_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat))); + } + public Task> Trades_historical_dataAsync(string symbolId, DateTime start, int limit) + { + return GetData>(CoinApiEndpointUrls.Trades_HistoricalData(symbolId, start.ToString(DateFormat), limit)); + } + + public Task> Quotes_current_data_allAsync() + { + var url = CoinApiEndpointUrls.Quotes_Current(); + return GetData>(url); + } + + public Task Quotes_current_data_symbolAsync(string symbolId) + { + var url = CoinApiEndpointUrls.Quotes_CurrentSymbol(symbolId); + return GetData(url); + } + + public Task> Quotes_latest_data_allAsync() + { + return GetData>(CoinApiEndpointUrls.Quotes_Latest()); + } + public Task> Quotes_latest_data_allAsync(int limit) + { + var url = CoinApiEndpointUrls.Quotes_Latest(limit); + return GetData>(url); + } + + public Task> Quotes_latest_data_symbolAsync(string symbolId) + { + var url = CoinApiEndpointUrls.Quotes_LatestSymbol(symbolId); + return GetData>(url); + } + public Task> Quotes_latest_data_symbolAsync(string symbolId, int limit) + { + var url = CoinApiEndpointUrls.Quotes_LatestSymbol(symbolId, limit); + return GetData>(url); + } + + public Task> Quotes_historical_dataAsync(string symbolId, DateTime start, DateTime end, int limit) + { + return GetData>(CoinApiEndpointUrls.Quotes_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat), limit)); + } + public Task> Quotes_historical_dataAsync(string symbolId, DateTime start) + { + return GetData>(CoinApiEndpointUrls.Quotes_HistoricalData(symbolId, start.ToString(DateFormat))); + } + public Task> Quotes_historical_dataAsync(string symbolId, DateTime start, DateTime end) + { + return GetData>(CoinApiEndpointUrls.Quotes_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat))); + } + public Task> Quotes_historical_dataAsync(string symbolId, DateTime start, int limit) + { + return GetData>(CoinApiEndpointUrls.Quotes_HistoricalData(symbolId, start.ToString(DateFormat), limit)); + + } + public Task> Orderbooks_current_data_all_filtered_bitstampAsync() + { + var url = CoinApiEndpointUrls.Orderbooks_CurrentFilteredBitstamp(); + return GetData>(url); + } + + public Task Orderbooks_current_data_symbolAsync(string symbolId) + { + var url = CoinApiEndpointUrls.Orderbooks_CurrentSymbol(symbolId); + return GetData(url); + } + + public Task> Orderbooks_last_dataAsync(string symbolId, int limit) + { + var url = CoinApiEndpointUrls.Orderbooks_LatestData(symbolId, limit); + return GetData>(url); + } + public Task> Orderbooks_last_dataAsync(string symbolId) + { + var url = CoinApiEndpointUrls.Orderbooks_LatestData(symbolId); + return GetData>(url); + } + + public Task> Orderbooks_historical_dataAsync(string symbolId, DateTime start, DateTime end, int limit) + { + return GetData>(CoinApiEndpointUrls.Orderbooks_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat), limit)); + } + public Task> Orderbooks_historical_dataAsync(string symbolId, DateTime start) + { + return GetData>(CoinApiEndpointUrls.Orderbooks_HistoricalData(symbolId, start.ToString(DateFormat))); + } + public Task> Orderbooks_historical_dataAsync(string symbolId, DateTime start, DateTime end) + { + return GetData>(CoinApiEndpointUrls.Orderbooks_HistoricalData(symbolId, start.ToString(DateFormat), end.ToString(DateFormat))); + } + public Task> Orderbooks_historical_dataAsync(string symbolId, DateTime start, int limit) + { + return GetData>(CoinApiEndpointUrls.Orderbooks_HistoricalData(symbolId, start.ToString(DateFormat), limit)); + } + + public Task> Orderbooks3_current_data_all_filtered_bitstampAsync() + { + return GetData>(CoinApiEndpointUrls.Orderbooks3_CurrentFilteredBitstamp()); + } + + public Task Orderbooks3_current_data_symbolAsync(string symbolId) + { + return GetData(CoinApiEndpointUrls.Orderbooks3_Current(symbolId)); + } + } + +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestEndpointsTester.cs b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestEndpointsTester.cs new file mode 100644 index 0000000000..e708fdb882 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/CoinApiRestEndpointsTester.cs @@ -0,0 +1,170 @@ +using CoinAPI.REST.V1.DataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 +{ + public class CoinApiRestEndpointsTester + { + private CoinApiRestClient _coinApi; + private string DateFormat => _coinApi.DateFormat; + + public Action Log { get; set; } + + public CoinApiRestEndpointsTester(string apikey, bool sandbox = false) + { + _coinApi = new CoinApiRestClient(apikey, sandbox); + } + + public CoinApiRestEndpointsTester(string apikey, string url) + { + _coinApi = new CoinApiRestClient(apikey, url); + } + + public Task>> Metadata_list_assets_iconsAsync(int iconSize) + { + return HandleCheck(CoinApiEndpointUrls.Assests_Icons(iconSize), _coinApi.Metadata_list_assets_iconsAsync(iconSize)); + } + + public Task>> Metadata_list_exchanges_iconsAsync(int iconSize) + { + return HandleCheck(CoinApiEndpointUrls.Exchanges_Icons(iconSize), _coinApi.Metadata_list_exchanges_iconsAsync(iconSize)); + } + + public Task>> Metadata_list_exchangesAsync() + { + return HandleCheck(CoinApiEndpointUrls.Exchanges(), _coinApi.Metadata_list_exchangesAsync()); + } + + public Task>> Metadata_list_assetsAsync() + { + return HandleCheck(CoinApiEndpointUrls.Assets(), _coinApi.Metadata_list_assetsAsync()); + } + + public Task> Exchange_rates_get_specific_rateAsync(string baseId, string quoteId) + { + return HandleCheck(CoinApiEndpointUrls.ExchangeRateSpecific(baseId, quoteId), _coinApi.Exchange_rates_get_specific_rateAsync(baseId, quoteId)); + } + + public Task> Exchange_rates_get_specific_rateAsync(string baseId, string quoteId, DateTime time) + { + return HandleCheck(CoinApiEndpointUrls.ExchangeRateSpecific(baseId, quoteId, time.ToString(DateFormat)), _coinApi.Exchange_rates_get_specific_rateAsync(baseId, quoteId, time)); + } + + public Task> Exchange_rates_get_all_current_ratesAsync(string baseId, bool invert = false) + { + return HandleCheck(CoinApiEndpointUrls.ExchangeRate(baseId, invert), _coinApi.Exchange_rates_get_all_current_ratesAsync(baseId, invert)); + } + + public Task>> Ohlcv_list_all_periodsAsync() + { + return HandleCheck(CoinApiEndpointUrls.Ohlcv_Periods(), _coinApi.Ohlcv_list_all_periodsAsync()); + } + + public Task>> Ohlcv_latest_dataAsync(string symbolId, string periodId) + { + return HandleCheck(CoinApiEndpointUrls.Ohlcv_LatestData(symbolId, periodId), _coinApi.Ohlcv_latest_dataAsync(symbolId, periodId)); + } + + public Task>> Ohlcv_historical_dataAsync(string symbolId, string periodId, DateTime start) + { + return HandleCheck(CoinApiEndpointUrls.Ohlcv_HistoricalData(symbolId, periodId, start.ToString(DateFormat)), _coinApi.Ohlcv_historical_dataAsync(symbolId, periodId, start)); + } + public Task>> Trades_latest_data_allAsync() + { + return HandleCheck(CoinApiEndpointUrls.Trades_Latest(), _coinApi.Trades_latest_data_allAsync()); + } + + public Task>> Trades_historical_dataAsync(string symbolId, DateTime start) + { + return HandleCheck(CoinApiEndpointUrls.Trades_HistoricalData(symbolId, start.ToString(DateFormat)), _coinApi.Trades_historical_dataAsync(symbolId, start)); + } + + public Task>> Trades_latest_data_symbolAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Trades_LatestSymbol(symbolId), _coinApi.Trades_latest_data_symbolAsync(symbolId)); + } + + public Task>> Quotes_current_data_allAsync() + { + return HandleCheck(CoinApiEndpointUrls.Quotes_Current(), _coinApi.Quotes_current_data_allAsync()); + } + + public Task> Quotes_current_data_symbolAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Quotes_CurrentSymbol(symbolId), _coinApi.Quotes_current_data_symbolAsync(symbolId)); + } + + public Task>> Quotes_latest_data_allAsync() + { + return HandleCheck(CoinApiEndpointUrls.Quotes_Latest(), _coinApi.Quotes_latest_data_allAsync()); + } + + public Task>> Quotes_latest_data_symbolAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Quotes_LatestSymbol(symbolId), _coinApi.Quotes_latest_data_symbolAsync(symbolId)); + } + + public Task>> Quotes_historical_dataAsync(string symbolId, DateTime start) + { + return HandleCheck(CoinApiEndpointUrls.Quotes_HistoricalData(symbolId, start.ToString(DateFormat)), _coinApi.Quotes_historical_dataAsync(symbolId, start)); + } + + public Task>> Orderbooks_current_data_all_filtered_bitstampAsync() + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks_CurrentFilteredBitstamp(), _coinApi.Orderbooks_current_data_all_filtered_bitstampAsync()); + } + + public Task> Orderbooks_current_data_symbolAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks_CurrentSymbol(symbolId), _coinApi.Orderbooks_current_data_symbolAsync(symbolId)); + } + + public Task>> Orderbooks_last_dataAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks_LatestData(symbolId), _coinApi.Orderbooks_last_dataAsync(symbolId)); + } + + public Task>> Orderbooks_historical_dataAsync(string symbolId, DateTime start) + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks_HistoricalData(symbolId, start.ToString(DateFormat)), _coinApi.Orderbooks_historical_dataAsync(symbolId, start)); + } + + + public Task>> Orderbooks3_current_data_all_filtered_bitstampAsync() + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks3_CurrentFilteredBitstamp(), _coinApi.Orderbooks3_current_data_all_filtered_bitstampAsync()); + } + + public Task> Orderbooks3_current_data_symbolAsync(string symbolId) + { + return HandleCheck(CoinApiEndpointUrls.Orderbooks3_Current(symbolId), _coinApi.Orderbooks3_current_data_symbolAsync(symbolId)); + } + + private async Task> HandleCheck(string endpoint, Task data) + { + var result = new EndpointCheckResult { Endpoint = endpoint }; + try + { + result.Data = await data; + result.StatusCode = CoinApiCheckStatusCode.GoodResponse; + + if (data == null) + result.StatusCode = CoinApiCheckStatusCode.BadData; + + if (data is IEnumerable list && !list.Any()) + result.StatusCode = CoinApiCheckStatusCode.BadData; + } + catch (Exception exception) + { + result.StatusCode = CoinApiCheckStatusCode.ExceptionThrown; + Log?.Invoke($"Endpoint {endpoint} check failed. Exception thrown: {exception.Message}"); + exception.Data.Add("Result", result); + throw exception; + } + return result; + } + } +} diff --git a/csharp-rest/DataModels/Ask.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Ask.cs similarity index 89% rename from csharp-rest/DataModels/Ask.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Ask.cs index d3fbf4703d..25f4e29794 100644 --- a/csharp-rest/DataModels/Ask.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Ask.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Ask { public decimal price { get; set; } public decimal size { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/AskL3.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/AskL3.cs new file mode 100644 index 0000000000..fe90d40f03 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/AskL3.cs @@ -0,0 +1,9 @@ +namespace CoinAPI.REST.V1 +{ + public class AskL3 + { + public string id { get; set; } + public decimal price { get; set; } + public decimal size { get; set; } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Asset.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Asset.cs new file mode 100644 index 0000000000..08e442298b --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Asset.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class Asset { + + + public string asset_id { get; set; } + public string name { get; set; } + public bool type_is_crypto { get; set; } + + public DateTime? data_start { get; set; } + public DateTime? data_end { get; set; } + public DateTime? data_quote_start { get; set; } + public DateTime? data_quote_end { get; set; } + public DateTime? data_orderbook_start { get; set; } + public DateTime? data_orderbook_end { get; set; } + public DateTime? data_trade_start { get; set; } + public DateTime? data_trade_end { get; set; } + public long? data_quote_count { get; set; } + public long? data_trade_count { get; set; } + public long? data_symbols_count { get; set; } + public decimal? volume_1hrs_usd { get; set; } + public decimal? volume_1day_usd { get; set; } + public decimal? volume_1mth_usd { get; set; } + public decimal? price_usd { get; set; } + + } +} diff --git a/csharp-rest/DataModels/Bid.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Bid.cs similarity index 89% rename from csharp-rest/DataModels/Bid.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Bid.cs index 7f1d639198..8b45e58987 100644 --- a/csharp-rest/DataModels/Bid.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Bid.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Bid { public decimal price { get; set; } public decimal size { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/BidL3.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/BidL3.cs new file mode 100644 index 0000000000..7232affdd0 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/BidL3.cs @@ -0,0 +1,9 @@ +namespace CoinAPI.REST.V1 +{ + public class BidL3 + { + public string id { get; set; } + public decimal price { get; set; } + public decimal size { get; set; } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ErrorMessage.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ErrorMessage.cs new file mode 100644 index 0000000000..9bb1834792 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ErrorMessage.cs @@ -0,0 +1,7 @@ +namespace CoinAPI.REST.V1 +{ + public class ErrorMessage + { + public string message { get; set; } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchange.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchange.cs new file mode 100644 index 0000000000..8cc2d06aae --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchange.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class Exchange { + public string exchange_id { get; set; } + public string website { get; set; } + public string name { get; set; } + public DateTime? data_start { get; set; } + public DateTime? data_end { get; set; } + public DateTime? data_quote_start { get; set; } + public DateTime? data_quote_end { get; set; } + public DateTime? data_orderbook_start { get; set; } + public DateTime? data_orderbook_end { get; set; } + public DateTime? data_trade_start { get; set; } + public DateTime? data_trade_end { get; set; } + public long? data_trade_count { get; set; } + public long? data_symbols_count { get; set; } + public decimal? volume_1hrs_usd { get; set; } + public decimal? volume_1day_usd { get; set; } + public decimal? volume_1mth_usd { get; set; } + + } +} diff --git a/csharp-rest/DataModels/ExchangeCurrentrate.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ExchangeCurrentrate.cs similarity index 90% rename from csharp-rest/DataModels/ExchangeCurrentrate.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ExchangeCurrentrate.cs index 20da03401b..35f854e296 100644 --- a/csharp-rest/DataModels/ExchangeCurrentrate.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/ExchangeCurrentrate.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class ExchangeCurrentrate { public string asset_id_base { get; set; } public Rate[] rates { get; set; } diff --git a/csharp-rest/DataModels/Exchangerate.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchangerate.cs similarity index 92% rename from csharp-rest/DataModels/Exchangerate.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchangerate.cs index affd8eb9de..099e0c1f79 100644 --- a/csharp-rest/DataModels/Exchangerate.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Exchangerate.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Exchangerate { public DateTime time { get; set; } public string asset_id_base { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Icon.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Icon.cs new file mode 100644 index 0000000000..fed22cb3a2 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Icon.cs @@ -0,0 +1,10 @@ +namespace CoinAPI.REST.V1.DataModels +{ + public class Icon + { + public string Id => exchange_id ?? asset_id; + public string exchange_id { get; set; } + public string asset_id { get; set; } + public string url { get; set; } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/OHLCV.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/OHLCV.cs new file mode 100644 index 0000000000..26de7be54e --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/OHLCV.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class OHLCV { + public DateTime time_period_start { get; set; } + public DateTime time_period_end { get; set; } + public DateTime time_open { get; set; } + public DateTime time_close { get; set; } + public decimal price_open { get; set; } + public decimal price_high { get; set; } + public decimal price_low { get; set; } + public decimal price_close { get; set; } + public decimal volume_traded { get; set; } + public int trades_count { get; set; } + } +} diff --git a/csharp-rest/DataModels/Orderbook.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook.cs similarity index 93% rename from csharp-rest/DataModels/Orderbook.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook.cs index da06505bca..6eac32f7a0 100644 --- a/csharp-rest/DataModels/Orderbook.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Orderbook { public string symbol_id { get; set; } public string time_exchange { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook3.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook3.cs new file mode 100644 index 0000000000..f98659c63d --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Orderbook3.cs @@ -0,0 +1,11 @@ +namespace CoinAPI.REST.V1 +{ + public class Orderbook3 + { + public string symbol_id { get; set; } + public string time_exchange { get; set; } + public string time_coinapi { get; set; } + public AskL3[] asks { get; set; } + public BidL3[] bids { get; set; } + } +} diff --git a/csharp-rest/DataModels/Period.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Period.cs similarity index 93% rename from csharp-rest/DataModels/Period.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Period.cs index 9f1b83df2d..d003b45633 100644 --- a/csharp-rest/DataModels/Period.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Period.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Period { public string period_id { get; set; } public int length_seconds { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Quote.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Quote.cs new file mode 100644 index 0000000000..d779ae6b2e --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Quote.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class Quote { + public string symbol_id { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public decimal ask_price { get; set; } + public decimal ask_size { get; set; } + public decimal bid_price { get; set; } + public decimal bid_size { get; set; } + public Trade last_trade { get; set; } + } +} diff --git a/csharp-rest/DataModels/Rate.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Rate.cs similarity index 91% rename from csharp-rest/DataModels/Rate.cs rename to data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Rate.cs index 8a84ffb9b1..ea26c334f0 100644 --- a/csharp-rest/DataModels/Rate.cs +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Rate.cs @@ -4,7 +4,7 @@ using System.Text; using System.Threading.Tasks; -namespace csharp_rest { +namespace CoinAPI.REST.V1 { public class Rate { public DateTime time { get; set; } public string asset_id_quote { get; set; } diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Symbol.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Symbol.cs new file mode 100644 index 0000000000..4cecab82e7 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Symbol.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class Symbol { + public string symbol_id { get; set; } + public string exchange_id { get; set; } + public string symbol_type { get; set; } + public bool option_type_is_call { get; set; } + public decimal option_strike_price { get; set; } + public decimal option_contract_unit { get; set; } + public string option_exercise_style { get; set; } + public DateTime option_expiration_time { get; set; } + public DateTime future_delivery_time { get; set; } + public string asset_id_base { get; set; } + public string asset_id_quote { get; set; } + public decimal? volume_1hrs { get; set; } + public decimal? volume_1hrs_usd { get; set; } + public decimal? volume_1day { get; set; } + public decimal? volume_1day_usd { get; set; } + public decimal? volume_1mth { get; set; } + public decimal? volume_1mth_usd { get; set; } + public decimal? price { get; set; } + public string symbol_id_exchange { get; set; } + public string asset_id_base_exchange { get; set; } + public string asset_id_quote_exchange { get; set; } + public decimal? price_precision { get; set; } + public decimal? size_precision { get; set; } + public DateTime? data_start { get; set; } + public DateTime? data_end { get; set; } + public DateTime? data_quote_start { get; set; } + public DateTime? data_quote_end { get; set; } + public DateTime? data_orderbook_start { get; set; } + public DateTime? data_orderbook_end { get; set; } + public DateTime? data_trade_start { get; set; } + public DateTime? data_trade_end { get; set; } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Trade.cs b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Trade.cs new file mode 100644 index 0000000000..e7ddffc95b --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Trade.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CoinAPI.REST.V1 { + public class Trade { + public string symbol_id { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public string uuid { get; set; } + public decimal price { get; set; } + public decimal size { get; set; } + public string taker_side { get; set; } + } + +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/EndpointCheckResult.cs b/data-api/csharp-rest/CoinAPI.REST.V1/EndpointCheckResult.cs new file mode 100644 index 0000000000..9f01113381 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/EndpointCheckResult.cs @@ -0,0 +1,9 @@ +namespace CoinAPI.REST.V1 +{ + public class EndpointCheckResult + { + public CoinApiCheckStatusCode StatusCode { get; set; } + public string Endpoint { get; set; } + public T Data { get; set; } + } +} diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/BadRequestException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/BadRequestException.cs new file mode 100644 index 0000000000..b354030428 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/BadRequestException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class BadRequestException : CoinApiException + { + public BadRequestException() + { + } + + public BadRequestException(string message) : base(message) + { + } + + public BadRequestException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/CoinApiException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/CoinApiException.cs new file mode 100644 index 0000000000..0bf3484587 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/CoinApiException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class CoinApiException : Exception + { + public CoinApiException() + { + } + + public CoinApiException(string message) : base(message) + { + } + + public CoinApiException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/ForbiddenException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/ForbiddenException.cs new file mode 100644 index 0000000000..d2160dea94 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/ForbiddenException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class ForbiddenException : CoinApiException + { + public ForbiddenException() + { + } + + public ForbiddenException(string message) : base(message) + { + } + + public ForbiddenException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/NoDataException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/NoDataException.cs new file mode 100644 index 0000000000..053701f484 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/NoDataException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class NoDataException : CoinApiException + { + public NoDataException() + { + } + + public NoDataException(string message) : base(message) + { + } + + public NoDataException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/TooManyRequestsException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/TooManyRequestsException.cs new file mode 100644 index 0000000000..af285595de --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/TooManyRequestsException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class TooManyRequestsException : CoinApiException + { + public TooManyRequestsException() + { + } + + public TooManyRequestsException(string message) : base(message) + { + } + + public TooManyRequestsException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/UnauthorizedException.cs b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/UnauthorizedException.cs new file mode 100644 index 0000000000..215e783e15 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.V1/Exceptions/UnauthorizedException.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.Serialization; + +namespace CoinAPI.REST.V1.Exceptions +{ + public class UnauthorizedException : CoinApiException + { + public UnauthorizedException() + { + } + + public UnauthorizedException(string message) : base(message) + { + } + + public UnauthorizedException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/data-api/csharp-rest/CoinAPI.REST.sln b/data-api/csharp-rest/CoinAPI.REST.sln new file mode 100644 index 0000000000..4d99442a98 --- /dev/null +++ b/data-api/csharp-rest/CoinAPI.REST.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29123.88 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoinAPI.REST.V1", "CoinAPI.REST.V1\CoinAPI.REST.V1.csproj", "{E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoinAPI.REST.V1.Example", "CoinAPI.REST.V1.Example\CoinAPI.REST.V1.Example.csproj", "{B8A15F62-52E6-4087-9C3E-98DAFAE00D35}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoinAPI.REST.V1.Tests", "CoinAPI.REST.V1.Tests\CoinAPI.REST.V1.Tests.csproj", "{BD2C0E09-9338-4138-8FB4-81ED002CB88C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7D2BCE4-B23E-4BDB-8836-D4DBB267B87B}.Release|Any CPU.Build.0 = Release|Any CPU + {B8A15F62-52E6-4087-9C3E-98DAFAE00D35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8A15F62-52E6-4087-9C3E-98DAFAE00D35}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8A15F62-52E6-4087-9C3E-98DAFAE00D35}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8A15F62-52E6-4087-9C3E-98DAFAE00D35}.Release|Any CPU.Build.0 = Release|Any CPU + {BD2C0E09-9338-4138-8FB4-81ED002CB88C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD2C0E09-9338-4138-8FB4-81ED002CB88C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD2C0E09-9338-4138-8FB4-81ED002CB88C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD2C0E09-9338-4138-8FB4-81ED002CB88C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8BC0B75C-4F2E-4635-8977-CBB54B2C7CF1} + EndGlobalSection +EndGlobal diff --git a/data-api/csharp-ws/.gitignore b/data-api/csharp-ws/.gitignore new file mode 100644 index 0000000000..62e4e8f2e1 --- /dev/null +++ b/data-api/csharp-ws/.gitignore @@ -0,0 +1,352 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/.gitignore b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/.gitignore new file mode 100644 index 0000000000..7d3a24e1aa --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/.gitignore @@ -0,0 +1 @@ +/config.json diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/CoinAPI.WebSocket.V1.Tests.csproj b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/CoinAPI.WebSocket.V1.Tests.csproj new file mode 100644 index 0000000000..ef530ac55f --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/CoinAPI.WebSocket.V1.Tests.csproj @@ -0,0 +1,27 @@ + + + + netcoreapp2.2 + + false + + + + + + + + + + + + + + + + + PreserveNewest + + + + diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestChangeHello.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestChangeHello.cs new file mode 100644 index 0000000000..c37b5b03ef --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestChangeHello.cs @@ -0,0 +1,99 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestChangeHello + { + [TestMethod] + public void TestTradesReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "trade", "quote" }, + subscribe_filter_exchange_id = new string[] { "COINBASE" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre_bs = new ManualResetEvent(false); + var mre_cb = new ManualResetEvent(false); + wsClient.TradeEvent += (s, i) => + { + if (i.symbol_id.StartsWith("GEMINI")) + { + mre_cb.Set(); + } + else if (i.symbol_id.StartsWith("COINBASE")) + { + mre_bs.Set(); + } + }; + wsClient.QuoteEvent += (s, i) => + { + if (i.symbol_id.StartsWith("GEMINI")) + { + mre_cb.Set(); + } + else if (i.symbol_id.StartsWith("COINBASE")) + { + mre_bs.Set(); + } + }; + + // BITSTAMP + wsClient.SendHelloMessage(helloMsg); + + if (!wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("should connect"); + } + + if (!mre_bs.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("bistamp should be"); + } + + if (mre_cb.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("coinbase should not"); + } + + // coinbase hello + helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "trade", "quote" }, + subscribe_filter_exchange_id = new string[] { "GEMINI" } + }; + + wsClient.SendHelloMessage(helloMsg); + + // received for coinbase - change of hello + mre_cb.Reset(); + + if (!mre_cb.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("dont received for coinbase"); + } + + mre_bs.Reset(); + + if (mre_bs.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("received for bitstapm after coinbase"); + } + + + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestExchangeRate.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestExchangeRate.cs new file mode 100644 index 0000000000..970e92e324 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestExchangeRate.cs @@ -0,0 +1,41 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestExchangeRate + { + [TestMethod] + public void TestExchangeRateReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "exrate" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.ExchangeRateEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOhlcv.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOhlcv.cs new file mode 100644 index 0000000000..303e6ad52a --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOhlcv.cs @@ -0,0 +1,41 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestOhlcv + { + [TestMethod] + public void TestOhlcvReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "ohlcv" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.OHLCVEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook.cs new file mode 100644 index 0000000000..48d34b3bc6 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook.cs @@ -0,0 +1,125 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestOrderBook + { + [TestMethod] + public void TestOrderBookReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "book" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.OrderBookEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + [TestMethod] + public void TestOrderBook5Receive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "book5" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using (var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.OrderBook5Event += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + [TestMethod] + public void TestOrderBook20Receive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "book20" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using (var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.OrderBook20Event += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + [TestMethod] + public void TestOrderBook50Receive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "book50" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using (var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.OrderBook50Event += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook3.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook3.cs new file mode 100644 index 0000000000..64ef409e05 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestOrderBook3.cs @@ -0,0 +1,42 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestOrderBook3 + { + [TestMethod] + public void TestOrderBook3Receive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "book_l3" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using (var wsClient = new CoinApiWsClient(isSandbox: true)) + { + var mre = new ManualResetEvent(false); + wsClient.OrderBookL3Event += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestQuote.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestQuote.cs new file mode 100644 index 0000000000..d03edc212e --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestQuote.cs @@ -0,0 +1,42 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestQuote + { + [TestMethod] + public void TestQuoteReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "quote" }, + subscribe_filter_symbol_id = new string[] { "BITSTAMP_SPOT_BTC_USD", "GEMINI_SPOT_BTC_USD", "COINBASE_SPOT_BTC_USD" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.QuoteEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestReconnect.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestReconnect.cs new file mode 100644 index 0000000000..b9fbbc7756 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestReconnect.cs @@ -0,0 +1,173 @@ +using CoinAPI.WebSocket.V1.DataModels; +using CoinAPI.WebSocket.V1.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Configuration; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestReconnections + { + [TestMethod] + public void TestMessageReceivedAfterReconnect() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "quote", "trade" } + }; + var timeout = TimeSpan.FromSeconds(10); + + using (var wsClient = new CoinApiWsClientReconnect(true)) + { + wsClient.Error += (s, e) => Debug.WriteLine(e.Message); + + var mre = new ManualResetEvent(false); + wsClient.TradeEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + wsClient.QuoteEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + if (!wsClient.ConnectedEvent.WaitOne(timeout)) + { + Assert.Fail("Connected not catched."); + } + + for (int i = 0; i < 10; i++) + { + mre.Reset(); + mssgCount = 0; + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + + Task.Run(() => wsClient.ForceReconnectUsedOnlyTestPurpose()); + if (!wsClient.ConnectedEvent.WaitOne(timeout)) + { + Assert.Fail("Reconnected not catched."); + } + } + } + } + + [TestMethod] + public void TestSilenceReconnect() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "quote", "trade" }, + subscribe_filter_exchange_id = new string[] { "EXCHANGETHATDOESNOTEXISTS" } + }; + + using (var wsClient = new CoinApiWsClientNoHb(false)) + { + var mre = new ManualResetEvent(false); + wsClient.TradeEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + wsClient.QuoteEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + Task.Run(() => wsClient.SendHelloMessage(helloMsg)); + if (!wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("Not connected ..."); + } + + for (int idx = 0; idx < 5; idx++) + { + if (!wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(30))) + { + Assert.Fail("He is not reconnecting..."); + } + else + { + Debug.WriteLine($"Reconnected @ {DateTime.UtcNow}"); + } + } + + if (mre.WaitOne(TimeSpan.FromSeconds(1))) + { + Assert.Fail("Received some message."); + } + + Assert.AreEqual(0, mssgCount); + } + } + + [TestMethod] + public void TestSilenceNoReconnect() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "quote", "trade" }, + subscribe_filter_exchange_id = new string[] { "EXCHANGETHATDOESNOTEXISTS" } + }; + + using (var wsClient = new CoinApiWsClient(false)) + { + var mre = new ManualResetEvent(false); + wsClient.TradeEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + wsClient.QuoteEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + Task.Run(() => wsClient.SendHelloMessage(helloMsg)); + if (!wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("Not connected ..."); + } + + if (mre.WaitOne(TimeSpan.FromSeconds(10))) + { + Assert.Fail("Received some message."); + } + + if (wsClient.ConnectedEvent.WaitOne(TimeSpan.FromSeconds(30))) + { + Assert.Fail("He is reconnecting..."); + } + + if (mre.WaitOne(TimeSpan.FromSeconds(1))) + { + Assert.Fail("Received some message."); + } + + Assert.AreEqual(0, mssgCount); + } + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTicker.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTicker.cs new file mode 100644 index 0000000000..7630da3da0 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTicker.cs @@ -0,0 +1,41 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestTicker + { + [TestMethod] + public void TestExchangeRateReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "ticker" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.TickerEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTrade.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTrade.cs new file mode 100644 index 0000000000..2157570d26 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestTrade.cs @@ -0,0 +1,41 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestTrade + { + [TestMethod] + public void TestTradesReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "trade" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.TradeEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(10)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestVolume.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestVolume.cs new file mode 100644 index 0000000000..0ae454ea08 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1.Tests/TestVolume.cs @@ -0,0 +1,41 @@ +using CoinAPI.WebSocket.V1.DataModels; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +namespace CoinAPI.WebSocket.V1.Tests +{ + [TestClass] + public class TestVolume + { + [TestMethod] + public void TestVolumeReceive() + { + var config = new ConfigurationBuilder().AddJsonFile("config.json").Build(); + + int mssgCount = 0; + var helloMsg = new Hello() + { + apikey = System.Guid.Parse(config["TestApiKey"]), + subscribe_data_type = new string[] { "volume" } + }; + + using(var wsClient = new CoinApiWsClient(true)) + { + var mre = new ManualResetEvent(false); + wsClient.VolumeEvent += (s, i) => + { + mre.Set(); + mssgCount++; + }; + + wsClient.SendHelloMessage(helloMsg); + + mre.WaitOne(TimeSpan.FromSeconds(50)); + Assert.AreNotEqual(0, mssgCount); + } + } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPI.WebSocket.V1.csproj b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPI.WebSocket.V1.csproj new file mode 100644 index 0000000000..ea0338ff5d --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPI.WebSocket.V1.csproj @@ -0,0 +1,34 @@ + + + + netstandard2.0 + true + CoinAPI.WebSocket.V1 + COINAPI LTD + CoinAPI.WebSocket + SDK for www.CoinAPI.io WebSocket API + https://www.CoinAPI.io + https://www.coinapi.io/img/favicon.png + https://github.com/coinapi/coinapi-sdk/ + GitHub.com + coinapi sdk websocket v1 api + en + LICENSE + COINAPI LTD + COINAPI LTD or its affiliates + 2.0.1 + + + + + + + + + + True + + + + + diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPIException.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPIException.cs new file mode 100644 index 0000000000..fa75172ee1 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinAPIException.cs @@ -0,0 +1,17 @@ +using CoinAPI.WebSocket.V1.DataModels; +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1 +{ + public class CoinAPIException : Exception + { + public CoinAPIException(string message) : base(message) + { + } + public CoinAPIException(Error error) : base(error.message) + { + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinApiWsClient.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinApiWsClient.cs new file mode 100644 index 0000000000..4c15d434fa --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/CoinApiWsClient.cs @@ -0,0 +1,313 @@ +using System; +using System.Diagnostics; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CoinAPI.WebSocket.V1.DataModels; +using Utf8Json; + +namespace CoinAPI.WebSocket.V1 +{ + public class CoinApiWsClient : ICoinApiWsClient, IDisposable + { + private static readonly int ReceiveBufferSize = 8192; + private const string UrlSandbox = "wss://ws-sandbox.coinapi.io/"; + private const string UrlProduction = "wss://ws.coinapi.io/"; + + private readonly string _url; + + private readonly CancellationTokenSource _cts = new CancellationTokenSource(); + private readonly QueueThread _queueThread = null; + + private readonly TimeSpan _hbTimeout = TimeSpan.FromSeconds(10); + private readonly TimeSpan _hbTimeoutCheckInterval = TimeSpan.FromSeconds(1); + private readonly TimeSpan _reconnectInterval = TimeSpan.FromSeconds(1); + private int _hbLastAction; + private int _hbLastActionMaxCount; + + // client reference is leaked here only for testing purposes (forcing reconnects) +#pragma warning disable IDE0069 // Disposable fields should be disposed + protected ClientWebSocket _client = null; +#pragma warning restore IDE0069 // Disposable fields should be disposed + + private Hello HelloMessage { get; set; } + public long UnprocessedMessagesQueueSize => _queueThread.QueueSize; + public event EventHandler Error; + public AutoResetEvent ConnectedEvent { get; } = new AutoResetEvent(false); + public DateTime? ConnectedTime { get; private set; } + protected bool? ForceOverrideHeartbeat { get; set; } = true; + + + public CoinApiWsClient(bool isSandbox, double hbTimeoutSecs, double reconnectIntervalSecs) : this(isSandbox) + { + _hbTimeout = TimeSpan.FromSeconds(hbTimeoutSecs); + _reconnectInterval = TimeSpan.FromSeconds(reconnectIntervalSecs); + } + + public CoinApiWsClient(bool isSandbox = false) : this(isSandbox ? UrlSandbox : UrlProduction) + { + } + + public CoinApiWsClient(string url) + { + _queueThread = new QueueThread(); + _queueThread.ItemDequeuedEvent += _queueThread_ItemDequeuedEvent; + _url = url; + } + + public void SendHelloMessage(Hello msg) + { + if (msg == null) + { + throw new ArgumentNullException(nameof(msg)); + } + + var startClient = HelloMessage == null; + + if (ForceOverrideHeartbeat.HasValue) + { + msg.heartbeat = ForceOverrideHeartbeat.Value; + } + HelloMessage = msg; + + if (startClient) + { + Task.Run(() => Connect()); + } + } + + private void _queueThread_ItemDequeuedEvent(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + + if (!data.type.TryParse(out var messageType)) + { + // unknown type + return; + } + + switch(messageType) + { + case MessageType.book: + HandleBookItem(sender, item); + break; + case MessageType.book5: + HandleBook5Item(sender, item); + break; + case MessageType.book20: + HandleBook20Item(sender, item); + break; + case MessageType.book50: + HandleBook50Item(sender, item); + break; + case MessageType.book_l3: + HandleBookL3Item(sender, item); + break; + case MessageType.ohlcv: + HandleOHLCVItem(sender, item); + break; + case MessageType.quote: + HandleQuoteItem(sender, item); + break; + case MessageType.trade: + HandleTradeItem(sender, item); + break; + case MessageType.volume: + HandleVolumeItem(sender, item); + break; + case MessageType.exrate: + HandleExchangeRateItem(sender, item); + break; + case MessageType.ticker: + HandleTickerItem(sender, item); + break; + case MessageType.error: + HandleErrorItem(sender, item); + break; + } + } + + private void HandleBookItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OrderBookEvent?.Invoke(sender, data); + } + private void HandleBook5Item(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OrderBook5Event?.Invoke(sender, data); + } + private void HandleBook20Item(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OrderBook20Event?.Invoke(sender, data); + } + private void HandleBook50Item(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OrderBook50Event?.Invoke(sender, data); + } + private void HandleBookL3Item(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OrderBookL3Event?.Invoke(sender, data); + } + + + private void HandleOHLCVItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OHLCVEvent?.Invoke(sender, data); + } + + private void HandleQuoteItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + QuoteEvent?.Invoke(sender, data); + } + + private void HandleTradeItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + TradeEvent?.Invoke(sender, data); + } + + private void HandleVolumeItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + VolumeEvent?.Invoke(sender, data); + } + + private void HandleExchangeRateItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + ExchangeRateEvent?.Invoke(sender, data); + } + + private void HandleTickerItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + TickerEvent?.Invoke(sender, data); + } + + private void HandleErrorItem(object sender, MessageData item) + { + var data = JsonSerializer.Deserialize(item.Data); + OnError(new CoinAPIException(data)); + } + + private async Task Connect() + { + while (!_cts.IsCancellationRequested) + { + using (var connectionCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token)) + { + await HandleConnection(connectionCts); + ConnectedTime = null; + connectionCts.Cancel(); + } + + await Task.Delay(_reconnectInterval); + } + } + + private async Task HeartbeatWatcher(ClientWebSocket client, CancellationTokenSource connectionCts) + { + // the quantity of loops that can be performed before timing out + _hbLastActionMaxCount = _hbTimeout.Seconds / _hbTimeoutCheckInterval.Seconds; + + while (!connectionCts.IsCancellationRequested) + { + // _hbLastAction is cleared by the connection worker, if we reach maxCount here means it hasn't gotten any message for a while + if (Interlocked.Increment(ref _hbLastAction) >= _hbLastActionMaxCount) + { + connectionCts.Cancel(); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, + nameof(HeartbeatWatcher), + CancellationToken.None); + continue; + } + await Task.Delay(_hbTimeoutCheckInterval, connectionCts.Token); + } + } + + private async Task HandleConnection(CancellationTokenSource connectionCts) + { + Interlocked.Exchange(ref _hbLastAction, 0); + + using (_client = new ClientWebSocket()) + { + try + { + _ = Task.Run(() => HeartbeatWatcher(_client, connectionCts)); + await _client.ConnectAsync(new Uri(_url), connectionCts.Token); + ConnectedTime = DateTime.UtcNow; + ConnectedEvent.Set(); + ConnectedEvent.Reset(); + Interlocked.Exchange(ref _hbLastAction, 0); + + var currentHello = HelloMessage; + var helloAs = new ArraySegment(JsonSerializer.Serialize(currentHello)); + await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); + Interlocked.Exchange(ref _hbLastAction, 0); + + var bufferArray = new byte[ReceiveBufferSize]; + while (_client.State == WebSocketState.Open && !connectionCts.IsCancellationRequested) + { + if (currentHello != HelloMessage) + { + currentHello = HelloMessage; + helloAs = new ArraySegment(JsonSerializer.Serialize(currentHello)); + await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); + Interlocked.Exchange(ref _hbLastAction, 0); + } + var messageData = await WSUtils.ReceiveMessage(_client, connectionCts.Token, bufferArray); + Interlocked.Exchange(ref _hbLastAction, 0); + + if (messageData.MessageType == WebSocketMessageType.Close) + { + return; + } + + _queueThread.Enqueue(messageData); + } + } + catch (TaskCanceledException) + { + await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal", CancellationToken.None); + } + catch (Exception ex) + { + OnError(ex); + } + } + } + + protected void OnError(Exception ex) + { + Error?.Invoke(this, ex); + } + + public void Dispose() + { + _queueThread.ItemDequeuedEvent -= _queueThread_ItemDequeuedEvent; + _queueThread.Dispose(); + + _cts.Cancel(); + _cts.Dispose(); + } + + public event OHLCVEventHandler OHLCVEvent; + public event OrderBookEventHandler OrderBookEvent; + public event OrderBook5EventHandler OrderBook5Event; + public event OrderBook20EventHandler OrderBook20Event; + public event OrderBook50EventHandler OrderBook50Event; + public event OrderBookL3EventHandler OrderBookL3Event; + public event QuoteEventHandler QuoteEvent; + public event TradeEventHandler TradeEvent; + public event VolumeEventHandler VolumeEvent; + public event ExchangeRateHandler ExchangeRateEvent; + public event TickerHandler TickerEvent; + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAsk.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAsk.cs new file mode 100644 index 0000000000..208ae21c45 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAsk.cs @@ -0,0 +1,8 @@ +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct BidAsk + { + public decimal price { get; set; } + public decimal size { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAskL3.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAskL3.cs new file mode 100644 index 0000000000..e97dc07626 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/BidAskL3.cs @@ -0,0 +1,12 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct BidAskL3 + { + public Guid id { get; set; } + public decimal price { get; set; } + public decimal size { get; set; } + public string update_type { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Error.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Error.cs new file mode 100644 index 0000000000..064e13daef --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Error.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public class Error + { + public string message { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/ExchangeRate.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/ExchangeRate.cs new file mode 100644 index 0000000000..5961c42d75 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/ExchangeRate.cs @@ -0,0 +1,12 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct ExchangeRate + { + public DateTime time { get; set; } + public string asset_id_base { get; set; } + public string asset_id_quote { get; set; } + public decimal rate { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Hello.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Hello.cs new file mode 100644 index 0000000000..4bb3ea81d7 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Hello.cs @@ -0,0 +1,17 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public class Hello + { + public Guid apikey { get; set; } + public bool heartbeat { get; set; } + public string[] subscribe_data_type { get; set; } + public string[] subscribe_filter_period_id { get; set; } + public string[] subscribe_filter_symbol_id { get; set; } + public string[] subscribe_filter_asset_id { get; set; } + public string[] subscribe_filter_exchange_id { get; set; } + public int? subscribe_update_limit_ms_quote { get; set; } + public int? subscribe_update_limit_ms_book_snapshot { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageBase.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageBase.cs new file mode 100644 index 0000000000..64b794c4f2 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageBase.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public class MessageBase + { + public string type { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageType.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageType.cs new file mode 100644 index 0000000000..d37b83fa1f --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/MessageType.cs @@ -0,0 +1,20 @@ +namespace CoinAPI.WebSocket.V1.DataModels +{ + internal enum MessageType + { + book, + book5, + book20, + book50, + book_l3, + hearbeat, + hello, + quote, + trade, + volume, + ohlcv, + error, + exrate, + ticker + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OHLCV.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OHLCV.cs new file mode 100644 index 0000000000..950d495007 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OHLCV.cs @@ -0,0 +1,21 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct OHLCV + { + public string symbol_id { get; set; } + public long sequence { get; set; } + public string period_id { get; set; } + public DateTime time_period_start { get; set; } + public DateTime time_period_end { get; set; } + public DateTime? time_open { get; set; } + public DateTime? time_close { get; set; } + public decimal? price_open { get; set; } + public decimal? price_high { get; set; } + public decimal? price_low { get; set; } + public decimal? price_close { get; set; } + public decimal volume_traded { get; set; } + public long trades_count { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook.cs new file mode 100644 index 0000000000..c1ba6e7996 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct OrderBook + { + public string symbol_id { get; set; } + public long sequence { get; set; } + public bool? is_snapshot { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public List asks { get; set; } + public List bids { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook3.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook3.cs new file mode 100644 index 0000000000..5bbbd676e1 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/OrderBook3.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct OrderBookL3 + { + public string symbol_id { get; set; } + public long sequence { get; set; } + public bool? is_snapshot { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public List asks { get; set; } + public List bids { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Quote.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Quote.cs new file mode 100644 index 0000000000..9aa5f57102 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Quote.cs @@ -0,0 +1,16 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct Quote + { + public string symbol_id { get; set; } + public long sequence { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public decimal ask_price { get; set; } + public decimal ask_size { get; set; } + public decimal bid_size { get; set; } + public decimal bid_price { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Ticker.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Ticker.cs new file mode 100644 index 0000000000..c8f68da58b --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Ticker.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct Ticker + { + public string symbol_id { get; set; } + public object last_quote { get; set; } + public object last_trade { get; set; } + public object last_ohlcv_5sec { get; set; } + public object last_ohlcv_15sec { get; set; } + public object last_ohlcv_1min { get; set; } + public object last_ohlcv_5min { get; set; } + public object last_ohlcv_15min { get; set; } + + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Trade.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Trade.cs new file mode 100644 index 0000000000..43f2f37cbb --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Trade.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct Trade + { + public string symbol_id { get; set; } + public long sequence { get; set; } + public DateTime time_exchange { get; set; } + public DateTime time_coinapi { get; set; } + public string uuid { get; set; } + public decimal price { get; set; } + public decimal size { get; set; } + public string taker_side { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Volume.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Volume.cs new file mode 100644 index 0000000000..c7dabaa523 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/DataModels/Volume.cs @@ -0,0 +1,19 @@ +using System; + +namespace CoinAPI.WebSocket.V1.DataModels +{ + public struct Volume + { + public DateTime time_coinapi { get; set; } + public string period_id { get; set; } + public SymbolVolume[] volume_by_symbol { get; set; } + } + public struct SymbolVolume + { + public string symbol_id { get; set; } + public string asset_id_base { get; set; } + public string asset_id_quote { get; set; } + public decimal volume_base { get; set; } + public decimal volume_quote { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/ICoinApiWsClient.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/ICoinApiWsClient.cs new file mode 100644 index 0000000000..31c604734b --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/ICoinApiWsClient.cs @@ -0,0 +1,33 @@ +using CoinAPI.WebSocket.V1.DataModels; + +namespace CoinAPI.WebSocket.V1 +{ + public delegate void OHLCVEventHandler(object sender, OHLCV item); + public delegate void OrderBookEventHandler(object sender, OrderBook item); + public delegate void OrderBook5EventHandler(object sender, OrderBook item); + public delegate void OrderBook20EventHandler(object sender, OrderBook item); + public delegate void OrderBook50EventHandler(object sender, OrderBook item); + public delegate void OrderBookL3EventHandler(object sender, OrderBookL3 item); + public delegate void QuoteEventHandler(object sender, Quote item); + public delegate void TradeEventHandler(object sender, Trade item); + public delegate void VolumeEventHandler(object sender, Volume item); + public delegate void ExchangeRateHandler(object sneder, ExchangeRate item); + public delegate void TickerHandler(object sender, Ticker item); + + public interface ICoinApiWsClient + { + void SendHelloMessage(Hello helloMessage); + long UnprocessedMessagesQueueSize { get; } + event OHLCVEventHandler OHLCVEvent; + event OrderBookEventHandler OrderBookEvent; + event OrderBook5EventHandler OrderBook5Event; + event OrderBook20EventHandler OrderBook20Event; + event OrderBook50EventHandler OrderBook50Event; + event OrderBookL3EventHandler OrderBookL3Event; + event QuoteEventHandler QuoteEvent; + event TradeEventHandler TradeEvent; + event VolumeEventHandler VolumeEvent; + event ExchangeRateHandler ExchangeRateEvent; + event TickerHandler TickerEvent; + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/MessageData.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/MessageData.cs new file mode 100644 index 0000000000..976901c79c --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/MessageData.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; + +namespace CoinAPI.WebSocket.V1 +{ + internal class MessageData + { + public byte[] Data { get; set; } + public WebSocketMessageType MessageType { get; set; } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/QueueThread.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/QueueThread.cs new file mode 100644 index 0000000000..7e3d7b9ee1 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/QueueThread.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace CoinAPI.WebSocket.V1 +{ + public class QueueThread : IDisposable + { + private readonly ManualResetEventSlim _messagesBufferEvent = new ManualResetEventSlim(false); + private readonly TimeSpan _messagesRouterTimeout = TimeSpan.FromSeconds(1); + private readonly int? _bufferCapacity; + private Thread _messagesRouterThread; + private readonly Queue _messagesBuffer = new Queue(); + + public delegate void ItemDequeuedEventHandler(object sender, T item); + public event ItemDequeuedEventHandler ItemDequeuedEvent; + + private readonly CancellationTokenSource _cts = new CancellationTokenSource(); + + public QueueThread(int? bufferCapacity = null) + { + _bufferCapacity = bufferCapacity; + _messagesRouterThread = new Thread(MessagesRouter_Thread) + { + IsBackground = true, + Name = GetType().FullName, + Priority = ThreadPriority.Highest + }; + _messagesRouterThread.Start(); + } + + public void Dispose() + { + _cts.Cancel(); + _cts.Dispose(); + } + + private void MessagesRouter_Thread() + { + T item; + while (!_cts.IsCancellationRequested) + { + try + { + _messagesBufferEvent.Wait(_messagesRouterTimeout, _cts.Token); + + do + { + lock (_messagesBuffer) + { + if (_messagesBuffer.Count == 0) + { + _messagesBufferEvent.Reset(); + break; + } + + item = _messagesBuffer.Dequeue(); + } + + ItemDequeuedEvent?.Invoke(this, item); + } + while (!_cts.IsCancellationRequested); + } + catch (Exception ex) + { + Debug.WriteLine(ex.ToString()); + } + } + } + + public bool Enqueue(T item) + { + lock (_messagesBuffer) + { + if (_bufferCapacity.HasValue && _messagesBuffer.Count >= _bufferCapacity.Value) + { + return false; + } + + _messagesBuffer.Enqueue(item); + } + + if(!_messagesBufferEvent.IsSet) + { + _messagesBufferEvent.Set(); + } + return true; + } + + public int QueueSize + { + get + { + lock (_messagesBuffer) + { + return _messagesBuffer.Count; + } + } + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientNoHb.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientNoHb.cs new file mode 100644 index 0000000000..d2e0eaff4b --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientNoHb.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CoinAPI.WebSocket.V1.Testing +{ + public class CoinApiWsClientNoHb : CoinApiWsClient + { + public CoinApiWsClientNoHb(bool isSandbox = false) : base(isSandbox) + { + ForceOverrideHeartbeat = false; + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientReconnect.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientReconnect.cs new file mode 100644 index 0000000000..4f7c3f8053 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/Testing/CoinApiWsClientReconnect.cs @@ -0,0 +1,29 @@ +using System; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CoinAPI.WebSocket.V1.DataModels; +using Utf8Json; + +namespace CoinAPI.WebSocket.V1.Testing +{ + public class CoinApiWsClientReconnect : CoinApiWsClient + { + public CoinApiWsClientReconnect(bool isSandbox = false) : base(isSandbox) + { + } + + public void ForceReconnectUsedOnlyTestPurpose() + { + try + { + _client.CloseAsync(WebSocketCloseStatus.NormalClosure, nameof(ForceReconnectUsedOnlyTestPurpose), CancellationToken.None).Wait(); + } + catch (Exception ex) + { + OnError(ex); + } + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.V1/WSUtils.cs b/data-api/csharp-ws/CoinAPI.WebSocket.V1/WSUtils.cs new file mode 100644 index 0000000000..7a8ff38118 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.V1/WSUtils.cs @@ -0,0 +1,115 @@ +using System; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.IO; +using CoinAPI.WebSocket.V1.DataModels; +using Utf8Json; + +namespace CoinAPI.WebSocket.V1 +{ + internal static class WSUtils + { + + internal async static Task ReceiveMessage( + System.Net.WebSockets.WebSocket webSocket, + CancellationToken ct, + byte[] bufferArray, + long maxSize = long.MaxValue) + { + ArraySegment buffer = new ArraySegment(bufferArray); + WebSocketReceiveResult result = null; + + using (var ms = new MemoryStream()) + { + do + { + result = await webSocket.ReceiveAsync(buffer, ct); + ms.Write(buffer.Array, buffer.Offset, result.Count); + if (ms.Length > maxSize) + { + throw new InvalidOperationException("Maximum size of the message was exceeded."); + } + } + while (!result.EndOfMessage); + + ms.Seek(0, SeekOrigin.Begin); + + return new MessageData + { + Data = ms.ToArray(), + MessageType = result.MessageType + }; + } + } + + public static T ParseMessage(MessageData messageData) + { + var jsonString = Encoding.ASCII.GetString(messageData.Data); + var messageObject = JsonSerializer.Deserialize(jsonString); + + return messageObject; + } + + public static async Task SendMessage(ArraySegment data, + System.Net.WebSockets.WebSocket webSocket) + { + await webSocket.SendAsync(data, WebSocketMessageType.Text, + endOfMessage: true, + cancellationToken: CancellationToken.None); + } + + public static bool TryParse(this string messageTypeStr, out MessageType messageType) + { + switch (messageTypeStr) + { + case "book": + messageType = MessageType.book; + return true; + case "book5": + messageType = MessageType.book5; + return true; + case "book20": + messageType = MessageType.book20; + return true; + case "book50": + messageType = MessageType.book50; + return true; + case "book_l3": + messageType = MessageType.book_l3; + return true; + case "hearbeat": + messageType = MessageType.hearbeat; + return true; + case "hello": + messageType = MessageType.hello; + return true; + case "quote": + messageType = MessageType.quote; + return true; + case "trade": + messageType = MessageType.trade; + return true; + case "volume": + messageType = MessageType.volume; + return true; + case "ohlcv": + messageType = MessageType.ohlcv; + return true; + case "error": + messageType = MessageType.error; + return true; + case "exrate": + messageType = MessageType.exrate; + return true; + case "ticker": + messageType = MessageType.ticker; + return true; + default: + messageType = MessageType.error; + return false; + } + } + } +} diff --git a/data-api/csharp-ws/CoinAPI.WebSocket.sln b/data-api/csharp-ws/CoinAPI.WebSocket.sln new file mode 100644 index 0000000000..11ee4046b0 --- /dev/null +++ b/data-api/csharp-ws/CoinAPI.WebSocket.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29123.88 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoinApi.WEBSOCKET.V1", "CoinAPI.WebSocket.V1\CoinAPI.WebSocket.V1.csproj", "{3A91EE7F-C11C-48E9-8260-6ABFE5C1953E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoinApi.WEBSOCKET.V1.Tests", "CoinAPI.WebSocket.V1.Tests\CoinAPI.WebSocket.V1.Tests.csproj", "{FD8A69DD-C3FE-4186-AA37-90B9FD4F97EB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3A91EE7F-C11C-48E9-8260-6ABFE5C1953E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3A91EE7F-C11C-48E9-8260-6ABFE5C1953E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3A91EE7F-C11C-48E9-8260-6ABFE5C1953E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3A91EE7F-C11C-48E9-8260-6ABFE5C1953E}.Release|Any CPU.Build.0 = Release|Any CPU + {FD8A69DD-C3FE-4186-AA37-90B9FD4F97EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FD8A69DD-C3FE-4186-AA37-90B9FD4F97EB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FD8A69DD-C3FE-4186-AA37-90B9FD4F97EB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FD8A69DD-C3FE-4186-AA37-90B9FD4F97EB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3806875C-51F9-45DD-9C98-C109695CA89B} + EndGlobalSection +EndGlobal diff --git a/data-api/go-rest/README.MD b/data-api/go-rest/README.MD new file mode 100644 index 0000000000..d26016b8d9 --- /dev/null +++ b/data-api/go-rest/README.MD @@ -0,0 +1,10 @@ +To run examples: + +```bash +cd /path/to/workspace +export GOPATH=/path/to/workspace +go get -u github.com/CoinAPI/coinapi-sdk/data-api/go-rest/v1 +wget -v https://raw.githubusercontent.com/coinapi/coinapi-sdk/master/go-rest/main.go +# update api key inside main.go +go run ./main.go +``` diff --git a/data-api/go-rest/main.go b/data-api/go-rest/main.go new file mode 100644 index 0000000000..d852d64483 --- /dev/null +++ b/data-api/go-rest/main.go @@ -0,0 +1,262 @@ +package main + +import ( + "encoding/json" + "fmt" + "time" +) + +import SDK "github.com/CoinAPI/coinapi-sdk/go-rest/v1" + +var API_KEY = "YOUR_API_KEY_HERE" + +func main() { + sdk := SDK.NewSDK(API_KEY) + + t, _ := time.Parse( + time.RFC3339, + "2016-11-01T22:08:41+00:00") + fmt.Println(t) + + exchanges, _ := sdk.Metadata_list_exchanges() + fmt.Println("exchanges:") + fmt.Println(" number:", len(exchanges)) + exchanges_item, _ := json.MarshalIndent(&exchanges[0], "", " ") + fmt.Println(" first items:", string(exchanges_item)) + + assets, _ := sdk.Metadata_list_assets() + fmt.Println("assets:") + fmt.Println("number:", len(assets)) + assets_item, _ := json.MarshalIndent(&assets[0], "", " ") + fmt.Println("first items:", string(assets_item)) + + spots, _, _, _ := sdk.Metadata_list_symbols() + fmt.Println("spots:") + fmt.Println("number:", len(spots)) + spots_item, _ := json.MarshalIndent(&spots[0], "", " ") + fmt.Println("first items:", string(spots_item)) + + _, futures, _, _ := sdk.Metadata_list_symbols() + fmt.Println("futures:") + fmt.Println("number:", len(futures)) + futures_item, _ := json.MarshalIndent(&futures[0], "", " ") + + _, _, options, _ := sdk.Metadata_list_symbols() + fmt.Println("options:") + fmt.Println("number:", len(options)) + options_item, _ := json.MarshalIndent(&options[0], "", " ") + fmt.Println("first items:", string(options_item)) + fmt.Println("first items:", string(futures_item)) + + exchange_rat_specific, _ := sdk.Exchange_rates_get_specific_rate("BTC", "USD") + fmt.Println("exchange_rat_specific:") + exchange_rat_specific_item, _ := json.MarshalIndent(&exchange_rat_specific, "", " ") + fmt.Println("first items:", string(exchange_rat_specific_item)) + + ex_rate_specific_with_time, _ := sdk.Exchange_rates_get_specific_rate_with_time("BTC", "USD", t) + fmt.Println("ex_rate_specific_with_time:") + ex_rate_specific_with_time_item, _ := json.MarshalIndent(&ex_rate_specific_with_time, "", " ") + fmt.Println("first items:", string(ex_rate_specific_with_time_item)) + + ex_rate_current_all_item, _ := sdk.Exchange_rates_get_all_current_rates("BTC") + fmt.Println("ex_rate_current_all_item:") + fmt.Println("number:", len(ex_rate_current_all_item)) + ex_rate_current_all_item_item, _ := json.MarshalIndent(&ex_rate_current_all_item[0], "", " ") + fmt.Println("first items:", string(ex_rate_current_all_item_item)) + + ohlvc_periods, _ := sdk.Ohlcv_list_all_periods() + fmt.Println("ohlvc_periods:") + fmt.Println("number:", len(ohlvc_periods)) + ohlvc_periods_item, _ := json.MarshalIndent(&ohlvc_periods[0], "", " ") + fmt.Println("first items:", string(ohlvc_periods_item)) + + ohlvc_latest_item, _ := sdk.Ohlcv_latest_data("BITSTAMP_SPOT_BTC_USD", "1MIN") + fmt.Println("ohlvc_latest_item:") + fmt.Println("number:", len(ohlvc_latest_item)) + ohlvc_latest_item_item, _ := json.MarshalIndent(&ohlvc_latest_item[0], "", " ") + fmt.Println("first items:", string(ohlvc_latest_item_item)) + + ohlvc_latest_with_limit, _ := sdk.Ohlcv_latest_data_with_limit("BITSTAMP_SPOT_BTC_USD", "1MIN", 5) + fmt.Println("ohlvc_latest_with_limit:") + fmt.Println("number:", len(ohlvc_latest_with_limit)) + ohlvc_latest_with_limit_item, _ := json.MarshalIndent(&ohlvc_latest_with_limit[0], "", " ") + fmt.Println("first items:", string(ohlvc_latest_with_limit_item)) + + Ohlcv_historic_data, _ := sdk.Ohlcv_historic_data("BITSTAMP_SPOT_BTC_USD", "1MIN", t) + fmt.Println("Ohlcv_historic_data:") + fmt.Println("number:", len(Ohlcv_historic_data)) + Ohlcv_historic_data_item, _ := json.MarshalIndent(&Ohlcv_historic_data[0], "", " ") + fmt.Println("first items:", string(Ohlcv_historic_data_item)) + + Ohlcv_historic_data_with_time_end_and_limit, _ := sdk.Ohlcv_historic_data_with_time_end_and_limit("BITSTAMP_SPOT_BTC_USD", "1MIN", t, time.Now(), 5) + fmt.Println("Ohlcv_historic_data_with_time_end_and_limit:") + fmt.Println("number:", len(Ohlcv_historic_data_with_time_end_and_limit)) + Ohlcv_historic_data_with_time_end_and_limit_item, _ := json.MarshalIndent(&Ohlcv_historic_data_with_time_end_and_limit[0], "", " ") + fmt.Println("first items:", string(Ohlcv_historic_data_with_time_end_and_limit_item)) + + Ohlcv_historic_data_with_time_end, _ := sdk.Ohlcv_historic_data_with_time_end("BITSTAMP_SPOT_BTC_USD", "1MIN", t, time.Now()) + fmt.Println("Ohlcv_historic_data_with_time_end:") + fmt.Println("number:", len(Ohlcv_historic_data_with_time_end)) + Ohlcv_historic_data_with_time_end_item, _ := json.MarshalIndent(&Ohlcv_historic_data_with_time_end[0], "", " ") + fmt.Println("first items:", string(Ohlcv_historic_data_with_time_end_item)) + + Ohlcv_historic_data_with_limit, _ := sdk.Ohlcv_historic_data_with_limit("BITSTAMP_SPOT_BTC_USD", "1MIN", t, 5) + fmt.Println("Ohlcv_historic_data_with_limit:") + fmt.Println("number:", len(Ohlcv_historic_data_with_limit)) + Ohlcv_historic_data_with_limit_item, _ := json.MarshalIndent(&Ohlcv_historic_data_with_limit[0], "", " ") + fmt.Println("first items:", string(Ohlcv_historic_data_with_limit_item)) + + Trades_latest_data_all, _ := sdk.Trades_latest_data_all() + fmt.Println("Trades_latest_data_all:") + fmt.Println("number:", len(Trades_latest_data_all)) + Trades_latest_data_all_item, _ := json.MarshalIndent(&Trades_latest_data_all[0], "", " ") + fmt.Println("first items:", string(Trades_latest_data_all_item)) + + Trades_latest_data_all_with_limit, _ := sdk.Trades_latest_data_all_with_limit(5) + fmt.Println("Trades_latest_data_all_with_limit:") + fmt.Println("number:", len(Trades_latest_data_all_with_limit)) + Trades_latest_data_all_with_limit_item, _ := json.MarshalIndent(&Trades_latest_data_all_with_limit[0], "", " ") + fmt.Println("first items:", string(Trades_latest_data_all_with_limit_item)) + + Trades_latest_data_symbol, _ := sdk.Trades_latest_data_symbol("BITSTAMP_SPOT_BTC_USD") + fmt.Println("Trades_latest_data_symbol:") + fmt.Println("number:", len(Trades_latest_data_symbol)) + Trades_latest_data_symbol_item, _ := json.MarshalIndent(&Trades_latest_data_symbol[0], "", " ") + fmt.Println("first items:", string(Trades_latest_data_symbol_item)) + + Trades_latest_data_symbol_with_limit, _ := sdk.Trades_latest_data_symbol_with_limit("BITSTAMP_SPOT_BTC_USD", 5) + fmt.Println("Trades_latest_data_symbol_with_limit:") + fmt.Println("number:", len(Trades_latest_data_symbol_with_limit)) + Trades_latest_data_symbol_with_limit_item, _ := json.MarshalIndent(&Trades_latest_data_symbol_with_limit[0], "", " ") + fmt.Println("first items:", string(Trades_latest_data_symbol_with_limit_item)) + + Trades_historical_data, _ := sdk.Trades_historical_data("BITSTAMP_SPOT_BTC_USD", t) + fmt.Println("Trades_historical_data:") + fmt.Println("number:", len(Trades_historical_data)) + Trades_historical_data_item, _ := json.MarshalIndent(&Trades_historical_data[0], "", " ") + fmt.Println("first items:", string(Trades_historical_data_item)) + + Trades_historical_data_with_limit, _ := sdk.Trades_historical_data_with_limit("BITSTAMP_SPOT_BTC_USD", t, 5) + fmt.Println("Trades_historical_data_with_limit:") + fmt.Println("number:", len(Trades_historical_data_with_limit)) + Trades_historical_data_with_limit_item, _ := json.MarshalIndent(&Trades_historical_data_with_limit[0], "", " ") + fmt.Println("first items:", string(Trades_historical_data_with_limit_item)) + + Trades_historical_data_with_time_end, _ := sdk.Trades_historical_data_with_time_end("BITSTAMP_SPOT_BTC_USD", t, time.Now()) + fmt.Println("Trades_historical_data_with_time_end:") + fmt.Println("number:", len(Trades_historical_data_with_time_end)) + Trades_historical_data_with_time_end_item, _ := json.MarshalIndent(&Trades_historical_data_with_time_end[0], "", " ") + fmt.Println("first items:", string(Trades_historical_data_with_time_end_item)) + + Trades_historical_data_with_time_end_and_limit, _ := sdk.Trades_historical_data_with_time_end_and_limit("BITSTAMP_SPOT_BTC_USD", t, time.Now(), 5) + fmt.Println("Trades_historical_data_with_time_end_and_limit:") + fmt.Println("number:", len(Trades_historical_data_with_time_end_and_limit)) + Trades_historical_data_with_time_end_and_limit_item, _ := json.MarshalIndent(&Trades_historical_data_with_time_end_and_limit[0], "", " ") + fmt.Println("first items:", string(Trades_historical_data_with_time_end_and_limit_item)) + + Quotes_current_data_all, _ := sdk.Quotes_current_data_all() + fmt.Println("Quotes_current_data_all:") + fmt.Println("number:", len(Quotes_current_data_all)) + Quotes_current_data_all_item, _ := json.MarshalIndent(&Quotes_current_data_all[0], "", " ") + fmt.Println("first items:", string(Quotes_current_data_all_item)) + + Quotes_current_data_symbol, _ := sdk.Quotes_current_data_symbol("BITSTAMP_SPOT_BTC_USD") + fmt.Println("Quotes_current_data_symbol:") + Quotes_current_data_symbol_item, _ := json.MarshalIndent(&Quotes_current_data_symbol, "", " ") + fmt.Println("first items:", string(Quotes_current_data_symbol_item)) + + Quotes_latest_data_all, _ := sdk.Quotes_latest_data_all() + fmt.Println("Quotes_latest_data_all:") + fmt.Println("number:", len(Quotes_latest_data_all)) + Quotes_latest_data_all_item, _ := json.MarshalIndent(&Quotes_latest_data_all[0], "", " ") + fmt.Println("first items:", string(Quotes_latest_data_all_item)) + + Quotes_latest_data_all_with_limit, _ := sdk.Quotes_latest_data_all_with_limit(5) + fmt.Println("Quotes_latest_data_all_with_limit:") + fmt.Println("number:", len(Quotes_latest_data_all_with_limit)) + Quotes_latest_data_all_with_limit_item, _ := json.MarshalIndent(&Quotes_latest_data_all_with_limit[0], "", " ") + fmt.Println("first items:", string(Quotes_latest_data_all_with_limit_item)) + + Quotes_latest_data_symbol, _ := sdk.Quotes_latest_data_symbol("BITSTAMP_SPOT_BTC_USD") + fmt.Println("Quotes_latest_data_symbol:") + fmt.Println("number:", len(Quotes_latest_data_symbol)) + Quotes_latest_data_symbol_item, _ := json.MarshalIndent(&Quotes_latest_data_symbol[0], "", " ") + fmt.Println("first items:", string(Quotes_latest_data_symbol_item)) + + Quotes_latest_data_symbol_with_limit, _ := sdk.Quotes_latest_data_symbol_with_limit("BITSTAMP_SPOT_BTC_USD", 5) + fmt.Println("Quotes_latest_data_symbol_with_limit:") + fmt.Println("number:", len(Quotes_latest_data_symbol_with_limit)) + Quotes_latest_data_symbol_with_limit_item, _ := json.MarshalIndent(&Quotes_latest_data_symbol_with_limit[0], "", " ") + fmt.Println("first items:", string(Quotes_latest_data_symbol_with_limit_item)) + + Quotes_historical_data, _ := sdk.Quotes_historical_data("BITSTAMP_SPOT_BTC_USD", t) + fmt.Println("Quotes_historical_data:") + fmt.Println("number:", len(Quotes_historical_data)) + Quotes_historical_data_item, _ := json.MarshalIndent(&Quotes_historical_data[0], "", " ") + fmt.Println("first items:", string(Quotes_historical_data_item)) + + Quotes_historical_data_with_limit, _ := sdk.Quotes_historical_data_with_limit("BITSTAMP_SPOT_BTC_USD", t, 5) + fmt.Println("Quotes_historical_data_with_limit:") + fmt.Println("number:", len(Quotes_historical_data_with_limit)) + Quotes_historical_data_with_limit_item, _ := json.MarshalIndent(&Quotes_historical_data_with_limit[0], "", " ") + fmt.Println("first items:", string(Quotes_historical_data_with_limit_item)) + + Quotes_historical_data_with_time_end, _ := sdk.Quotes_historical_data_with_time_end("BITSTAMP_SPOT_BTC_USD", t, time.Now()) + fmt.Println("Quotes_historical_data_with_time_end:") + fmt.Println("number:", len(Quotes_historical_data_with_time_end)) + Quotes_historical_data_with_time_end_item, _ := json.MarshalIndent(&Quotes_historical_data_with_time_end[0], "", " ") + fmt.Println("first items:", string(Quotes_historical_data_with_time_end_item)) + + Quotes_historical_data_with_time_end_and_limit, _ := sdk.Quotes_historical_data_with_time_end_and_limit("BITSTAMP_SPOT_BTC_USD", t, time.Now(), 5) + fmt.Println("Quotes_historical_data_with_time_end_and_limit:") + fmt.Println("number:", len(Quotes_historical_data_with_time_end_and_limit)) + Quotes_historical_data_with_time_end_and_limit_item, _ := json.MarshalIndent(&Quotes_historical_data_with_time_end_and_limit[0], "", " ") + fmt.Println("first items:", string(Quotes_historical_data_with_time_end_and_limit_item)) + + Orderbooks_current_data_all, _ := sdk.Orderbooks_current_data_all() + fmt.Println("Orderbooks_current_data_all:") + fmt.Println("number:", len(Orderbooks_current_data_all)) + Orderbooks_current_data_all_item, _ := json.MarshalIndent(&Orderbooks_current_data_all[0], "", " ") + fmt.Println("first items:", string(Orderbooks_current_data_all_item)) + + Orderbooks_current_data_symbol, _ := sdk.Orderbooks_current_data_symbol("BITSTAMP_SPOT_BTC_USD") + fmt.Println("Orderbooks_current_data_symbol:") + Orderbooks_current_data_symbol_item, _ := json.MarshalIndent(&Orderbooks_current_data_symbol, "", " ") + fmt.Println("first items:", string(Orderbooks_current_data_symbol_item)) + + Orderbooks_latest_data_all, _ := sdk.Orderbooks_latest_data("BITSTAMP_SPOT_BTC_USD") + fmt.Println("Orderbooks_latest_data_all:") + fmt.Println("number:", len(Orderbooks_latest_data_all)) + Orderbooks_latest_data_all_item, _ := json.MarshalIndent(&Orderbooks_latest_data_all[0], "", " ") + fmt.Println("first items:", string(Orderbooks_latest_data_all_item)) + + Orderbooks_latest_data_all_with_limit, _ := sdk.Orderbooks_latest_data_with_limit("BITSTAMP_SPOT_BTC_USD", 5) + fmt.Println("Orderbooks_latest_data_all_with_limit:") + fmt.Println("number:", len(Orderbooks_latest_data_all_with_limit)) + Orderbooks_latest_data_all_with_limit_item, _ := json.MarshalIndent(&Orderbooks_latest_data_all_with_limit[0], "", " ") + fmt.Println("first items:", string(Orderbooks_latest_data_all_with_limit_item)) + + Orderbooks_historical_data, _ := sdk.Orderbooks_historical_data("BITSTAMP_SPOT_BTC_USD", t) + fmt.Println("Orderbooks_historical_data:") + fmt.Println("number:", len(Orderbooks_historical_data)) + Orderbooks_historical_data_item, _ := json.MarshalIndent(&Orderbooks_historical_data[0], "", " ") + fmt.Println("first items:", string(Orderbooks_historical_data_item)) + + Orderbooks_historical_data_with_limit, _ := sdk.Orderbooks_historical_data_with_limit("BITSTAMP_SPOT_BTC_USD", t, 5) + fmt.Println("Orderbooks_historical_data_with_limit:") + fmt.Println("number:", len(Orderbooks_historical_data_with_limit)) + Orderbooks_historical_data_with_limit_item, _ := json.MarshalIndent(&Orderbooks_historical_data_with_limit[0], "", " ") + fmt.Println("first items:", string(Orderbooks_historical_data_with_limit_item)) + + Orderbooks_historical_data_with_time_end, _ := sdk.Orderbooks_historical_data_with_time_end("BITSTAMP_SPOT_BTC_USD", t, time.Now()) + fmt.Println("Orderbooks_historical_data_with_time_end:") + fmt.Println("number:", len(Orderbooks_historical_data_with_time_end)) + Orderbooks_historical_data_with_time_end_item, _ := json.MarshalIndent(&Orderbooks_historical_data_with_time_end[0], "", " ") + fmt.Println("first items:", string(Orderbooks_historical_data_with_time_end_item)) + + Orderbooks_historical_data_with_time_end_and_limit, _ := sdk.Orderbooks_historical_data_with_time_end_and_limit("BITSTAMP_SPOT_BTC_USD", t, time.Now(), 5) + fmt.Println("Orderbooks_historical_data_with_time_end_and_limit:") + fmt.Println("number:", len(Orderbooks_historical_data_with_time_end_and_limit)) + Orderbooks_historical_data_with_time_end_and_limit_item, _ := json.MarshalIndent(&Orderbooks_historical_data_with_time_end_and_limit[0], "", " ") + fmt.Println("first items:", string(Orderbooks_historical_data_with_time_end_and_limit_item)) +} diff --git a/go-rest/v1/coinapi_v1.go b/data-api/go-rest/v1/coinapi_v1.go similarity index 91% rename from go-rest/v1/coinapi_v1.go rename to data-api/go-rest/v1/coinapi_v1.go index 1818a37ebe..47c3852570 100644 --- a/go-rest/v1/coinapi_v1.go +++ b/data-api/go-rest/v1/coinapi_v1.go @@ -21,7 +21,7 @@ type Exchange struct { type Asset struct { Asset_id string `json:"asset_id"` Name string `json:"name"` - Type_is_crypto bool `json:"type_is_crypto"` + Type_is_crypto int `json:"type_is_crypto"` } type SymbolBase struct { @@ -467,45 +467,6 @@ func (sdk SDK) Orderbooks_historical_data_with_time_end_and_limit(symbol_id stri // orderbooks end -// twitter -func (sdk SDK) Twitter_latest_data() (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/latest") - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -func (sdk SDK) Twitter_latest_data_with_limit(limit uint32) (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/latest?limit=%d", limit) - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -func (sdk SDK) Twitter_historical_data(time_start time.Time) (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/history?time_start=%s", time_start.Format(time.RFC3339)) - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -func (sdk SDK) Twitter_historical_data_with_limit(time_start time.Time, limit uint32) (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/history?time_start=%s&limit=%d", time_start.Format(time.RFC3339), limit) - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -func (sdk SDK) Twitter_historical_data_with_time_end(time_start time.Time, time_end time.Time) (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/history?time_start=%s&time_end=%s", time_start.Format(time.RFC3339), time_end.Format(time.RFC3339)) - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -func (sdk SDK) Twitter_historical_data_with_time_end_and_limit(time_start time.Time, time_end time.Time, limit uint32) (tweets []Tweet, err error) { - path := fmt.Sprintf("/v1/twitter/history?time_start=%s&time_end=%s&limit=%d", time_start.Format(time.RFC3339), time_end.Format(time.RFC3339), limit) - err = sdk.do_request_and_unmarshal(path, &tweets) - return -} - -// twitter end - func (sdk SDK) do_request_and_unmarshal(path string, o interface{}) (err error) { text, req_err := sdk.get_response_text(path) if req_err != nil { @@ -546,7 +507,6 @@ func (sdk SDK) get_response_text(path string) (responseBody string, err error) { } return "", fmt.Errorf("Server responded with status code: %d", resp.StatusCode) } - fmt.Println("response:", string(body)) return string(body), nil } diff --git a/data-api/go-ws/README.md b/data-api/go-ws/README.md new file mode 100644 index 0000000000..dbaa46c765 --- /dev/null +++ b/data-api/go-ws/README.md @@ -0,0 +1,23 @@ + + +## Installation + +Install the following dependencies: + +```shell +go mod download github.com/bitly/go-simplejson +go mod download github.com/shopspring/decimal +go mod download github.com/gorilla/websocket +``` + + +## Run examples: + +```bash +cd /path/to/workspace +export GOPATH=/path/to/workspace +go get -u github.com/CoinAPI/coinapi-sdk/data-api/go-ws +wget -v https://raw.githubusercontent.com/coinapi/coinapi-sdk/master/go-ws/main.go +# update api key inside main.go +go run ./main.go +``` diff --git a/data-api/go-ws/api/sdk.go b/data-api/go-ws/api/sdk.go new file mode 100644 index 0000000000..a6736b2a03 --- /dev/null +++ b/data-api/go-ws/api/sdk.go @@ -0,0 +1,10 @@ +package api + +import . "go-ws/api/types" + +func NewSDK(apiKey string) (sdk SDK) { + validateApiKey(apiKey) + config := getSDKConfig(apiKey) + sdk = getSDK(config) + return sdk +} diff --git a/data-api/go-ws/api/types/config.go b/data-api/go-ws/api/types/config.go new file mode 100644 index 0000000000..93170932c0 --- /dev/null +++ b/data-api/go-ws/api/types/config.go @@ -0,0 +1,16 @@ +package types + +type SdkConfig struct { + ApiKey string + ApiVersion ApiVersion + EnvironmentType EnvironmentType + ReconnectType ReconnectType +} + +// WsConfig webservice configuration +type WsConfig struct { + ApiKey string + Endpoint string + WebsocketKeepalive bool + WebsocketTimeout int +} diff --git a/data-api/go-ws/api/types/enums.go b/data-api/go-ws/api/types/enums.go new file mode 100644 index 0000000000..271abc1a30 --- /dev/null +++ b/data-api/go-ws/api/types/enums.go @@ -0,0 +1,48 @@ +package types + +// ApiVersion custom ENUM for SDK forward compatibility +type ApiVersion int + +const ( + ApiV1 ApiVersion = iota +) + +// EnvironmentType +// https://docs.coinapi.io/#endpoints-2 +type EnvironmentType int + +const ( + ProdEncrypted EnvironmentType = iota + ProdInsecure + TestEncrypted + TestInsecure +) + +// MessageType replicates the official incoming message types as (kinda) string enum. +// https://docs.coinapi.io/#messages +type MessageType string + +const ( + TRADE MessageType = "trade" + QUOTE MessageType = "quote" + BOOK_L2_FULL MessageType = "book" // Orderbook L2 (Full) + BOOK_L2_TOP_5 MessageType = "book5" // Orderbook L2 (5 best Bid / Ask) + BOOK_L2_TOP_20 MessageType = "book20" // Orderbook L2 (20 best Bid / Ask) + BOOK_L2_TOP_50 MessageType = "book50" // Orderbook L2 (50 best Bid / Ask) + BOOK_L3_FULL MessageType = "book_l3" // Orderbook L3 (Full) https://docs.coinapi.io/#orderbook-l3-full-in + OHLCV MessageType = "ohlcv" + VOLUME MessageType = "volume" + HEARTBEAT MessageType = "hearbeat" // DO NOT FIX! it's a typo in the official msg spec! + ERROR MessageType = "error" // Otherwise processMessage(.) fails to handle heartbeat messages! + EXCHANGERATE MessageType = "exrate" + RECONNECT MessageType = "reconnect" +) + +// ReconnectType defines the reconnect behavior upon receiving a reconnect message +// https://docs.coinapi.io/#reconnect-in +type ReconnectType int + +const ( + OnConnectionClose ReconnectType = iota + OnReconnectMessage +) diff --git a/data-api/go-ws/api/types/functions.go b/data-api/go-ws/api/types/functions.go new file mode 100644 index 0000000000..95de876eec --- /dev/null +++ b/data-api/go-ws/api/types/functions.go @@ -0,0 +1,11 @@ +package types + +// InvokeFunction is a unified function type for all event handlers. +// https://yourbasic.org/golang/function-pointer-type-declaration/ +type InvokeFunction func(message *DataMessage) (err error) + +// WsHandler handle raw websocket message +type WsHandler func(message []byte) + +// WsErrHandler handles raw websocket errors +type WsErrHandler func(err error) diff --git a/data-api/go-ws/api/types/interface.go b/data-api/go-ws/api/types/interface.go new file mode 100644 index 0000000000..83a96159eb --- /dev/null +++ b/data-api/go-ws/api/types/interface.go @@ -0,0 +1,23 @@ +package types + +type SDK interface { + SendHello(hello *Hello) (err error) + OpenConnection() (err error) + CloseConnection() (err error) + // ResetConnection hard reset: closes current connection, opens a new one, + // and resends the last hello message. No message buffering! + ResetConnection() (err error) + + // sys handlers + SetErrorInvoke(function InvokeFunction) + SetHeartBeatInvoke(function InvokeFunction) + SetReconnectInvoke(function InvokeFunction) + + // Data handlers + SetExRateInvoke(function InvokeFunction) + SetTradesInvoke(function InvokeFunction) + SetQuoteInvoke(function InvokeFunction) + SetBookInvoke(function InvokeFunction) + SetOHLCVInvoke(function InvokeFunction) + SetVolumeInvoke(function InvokeFunction) +} diff --git a/data-api/go-ws/api/types/messages.go b/data-api/go-ws/api/types/messages.go new file mode 100644 index 0000000000..0c368c1b0f --- /dev/null +++ b/data-api/go-ws/api/types/messages.go @@ -0,0 +1,358 @@ +package types + +import ( + "bytes" + "encoding/json" + "fmt" + "github.com/shopspring/decimal" + "log" + "time" +) + +// DataMessage composite type substitutes missing type inheritance. +type DataMessage struct { + Type *MessageType + ErrorMessage *ErrorMessage + ExchangeRate *ExchangeRate + Orderbook *OrderBook + Ohlcv *Ohlcv + Quote *Quote + Reconnect *Reconnect + Hearbeat *Heartbeat + Trade *Trade + Volume *Volume +} + +func (s DataMessage) String() string { + return fmt.Sprintf("{Type: %v, ErrorMessage: %v, ExchangeRate %v, Orderbook: %v, Ohlcv: %v, Quote: %v, Reconnect: %v, Reconnect: %v, Hearbeat: %v, Trade: %v, Volume: %v}", + s.Type, + s.ErrorMessage, + s.ExchangeRate, + s.Orderbook, + s.Ohlcv, + s.Quote, + s.Reconnect, + s.Hearbeat, + s.Trade, + s.Volume, + ) +} + +// Ask subtype for OrderBook +type Ask struct { + Type MessageType `json:"type"` + Price decimal.Decimal `json:"price"` + Size decimal.Decimal `json:"size"` +} + +func (s Ask) String() string { + return fmt.Sprintf("{Type: %v, Price: %v, Size: %v}", + s.Type, + s.Price, + s.Size, + ) +} + +// Bid subtype for OrderBook +type Bid struct { + Type MessageType `json:"type"` + Price decimal.Decimal `json:"price"` + Size decimal.Decimal `json:"size"` +} + +func (s Bid) String() string { + return fmt.Sprintf("{Type: %v, Price: %v, Size: %v}", + s.Type, + s.Price, + s.Size, + ) +} + +// ErrorMessage expect that the underlying WebSocket connection will be closed by us after sending an error message. +// https://docs.coinapi.io/#error-handling +type ErrorMessage struct { + Type MessageType `json:"type"` + Message string `json:"message"` +} + +func (s ErrorMessage) String() string { + return fmt.Sprintf("{Type: %v, Message: %v}", + s.Type, + s.Message, + ) +} + +// ExchangeRate message delivering updates of (VWAP-24H) Volume Weighted Average Price between pair of assets +// https://docs.coinapi.io/#exchange-rate-in +type ExchangeRate struct { + Type MessageType `json:"type"` + Asset_id_base string `json:"asset_id_base"` + Asset_id_quote string `json:"asset_id_quote"` + Time time.Time `json:"time"` + Rate decimal.Decimal `json:"rate"` +} + +func (s ExchangeRate) String() string { + return fmt.Sprintf("{Type: %v, Asset_id_base: %v, Asset_id_quote: %v Time: %v, Rate: %v, }", + s.Type, + s.Asset_id_base, + s.Asset_id_quote, + s.Time, + s.Rate, + ) +} + +// Hello After your WebSocket connection is established, you must send us a Hello message which contains: +// * Stream preferences +// * API key for authorization +// If your message will be incorrect, we will send you error message and disconnect connection afterwards. +// Hello message can be repeated, each one will cause subscription scope override without interruption of your WebSocket connection. +// https://docs.coinapi.io/#hello-out +type Hello struct { + Type MessageType `json:"type"` + Api_key string `json:"apikey"` + Heartbeat bool `json:"heartbeat"` + Subscribe_data_type []string `json:"subscribe_data_type"` + Subscribe_filter_symbol_id []string `json:"subscribe_filter_symbol_id"` + Subscribe_filter_asset_id []string `json:"subscribe_filter_asset_id"` + Subscribe_filter_period_id []string `json:"subscribe_filter_period_id"` + Subscribe_filter_exchange_id []string `json:"subscribe_filter_exchange_id"` + Subscribe_update_limit_ms_quote uint32 `json:"subscribe_update_limit_ms_quote"` + Subscribe_update_limit_ms_book_snapshot uint32 `json:"subscribe_update_limit_ms_book_snapshot"` +} + +func (s Hello) String() string { + return fmt.Sprintf("{Type: %v, Api_key: %v, Heartbeat: %v Subscribe_data_type: %v, Subscribe_filter_symbol_id: %v, Subscribe_filter_asset_id: %v, Subscribe_filter_period_id: %v, Subscribe_filter_exchange_id: %v, Subscribe_update_limit_ms_quote: %v, Subscribe_update_limit_ms_book_snapshot: %v}", + s.Type, + s.Api_key, + s.Heartbeat, + s.Subscribe_data_type, + s.Subscribe_filter_symbol_id, + s.Subscribe_filter_asset_id, + s.Subscribe_filter_period_id, + s.Subscribe_filter_exchange_id, + s.Subscribe_update_limit_ms_quote, + s.Subscribe_update_limit_ms_book_snapshot, + ) +} +func (s Hello) GetJSON() (b []byte, err error) { + + b, err = json.Marshal(s) + if err != nil { + log.Println("Error marshaling Hello object") + log.Println(err) + return nil, err + } + + var prettyJSON bytes.Buffer + err = json.Indent(&prettyJSON, b, "", "\t") + if err != nil { + log.Println("Error making JSON pretty") + log.Println(err) + return nil, err + } + + return b, nil +} + +func (s Hello) PrintJSON() { + b, err := s.GetJSON() + if err != nil { + log.Println(err) + } + println(string(b)) + +} + +// OrderBook Book message is sent for each snapshot or update of the order book. +// After subscription to this data type is initialized, we immediately start delivering updates to the order book +// and at least one snapshot will be provided as soon as possible with the nearest update of the book. +// Book message represents total amount of bids and asks aggregated by price level. +// https://docs.coinapi.io/#orderbook-l2-full-in +type OrderBook struct { + Type MessageType `json:"type"` + Symbol_id string `json:"symbol_id"` + Sequence uint32 `json:"sequence"` + Time_exchange time.Time `json:"time_exchange"` + Time_coinapi time.Time `json:"time_coinapi"` + Asks []Bid `json:"asks"` + Bids []Bid `json:"bids"` +} + +func (s OrderBook) String() string { + return fmt.Sprintf(" { MessageType: %v, Symbol_id: %v, Sequence: %v, Time_exchange: %v, Time_coinapi: %v, Asks: %v, Bids: %v, }", + s.Type, + s.Symbol_id, + s.Sequence, + s.Time_exchange, + s.Time_coinapi, + s.Asks, + s.Bids, + ) +} + +// Ohlcv A OHLCV message is sent for each update on the periods between 1SEC and 1MIN. +// https://docs.coinapi.io/#ohlcv-in +type Ohlcv struct { + Type MessageType `json:"type"` + Symbol_id string `json:"symbol_id"` + Sequence uint32 `json:"sequence"` + PeriodID string `json:"period_id"` + Time_period_start time.Time `json:"time_period_start"` + Time_period_end time.Time `json:"time_period_end"` + Time_open time.Time `json:"time_open"` + Time_close time.Time `json:"time_close"` + Price_open decimal.Decimal `json:"price_open"` + Price_high decimal.Decimal `json:"price_high"` + Price_low decimal.Decimal `json:"price_low"` + Price_close decimal.Decimal `json:"price_close"` + Volume_traded decimal.Decimal `json:"volume_traded"` + Trades_count uint32 `json:"trades_count"` +} + +func (s Ohlcv) String() string { + return fmt.Sprintf(" {Type: %v, Symbol_id: %v, Sequence: %v, Time_period_start: %v, Time_period_start: %v, Time_period_end: %v, Time_open: %v, Time_close: %v, Price_open: %v, Price_high: %v, Price_low: %v,Price_close: %v, Volume_traded: %v, Trades_count: %v}", + s.Type, + s.Symbol_id, + s.Sequence, + s.PeriodID, + s.Time_period_start, + s.Time_period_end, + s.Time_open, + s.Time_close, + s.Price_open, + s.Price_high, + s.Price_low, + s.Price_close, + s.Volume_traded, + s.Trades_count, + ) +} + +// Quote Quote message is sent for each update on orderbook first best bid or ask level. +// https://docs.coinapi.io/#quotes-in +type Quote struct { + Type MessageType `json:"type"` + Symbol_id string `json:"symbol_id"` + Sequence uint32 `json:"sequence"` + Time_exchange time.Time `json:"time_exchange"` + Time_coinapi time.Time `json:"time_coinapi"` + Ask_price decimal.Decimal `json:"ask_price"` + Ask_size decimal.Decimal `json:"ask_size"` + Bid_price decimal.Decimal `json:"bid_price"` + Bid_size decimal.Decimal `json:"bid_size"` +} + +func (s Quote) String() string { + return fmt.Sprintf(" {Type: %v, Symbol_id: %v, Sequence: %v, Time_exchange: %v, Time_coinapi: %v, Ask_price: %v, Ask_siz: %v, Bid_price: %v, Bid_size: %v}", + s.Type, + s.Symbol_id, + s.Sequence, + s.Time_exchange, + s.Time_coinapi, + s.Ask_price, + s.Ask_size, + s.Bid_price, + s.Bid_size, + ) +} + +// Reconnect message is sent by the server to all connected clients when the server will be restarted or shut down at the defined exact time included in the message content. After the period specified in message passes, +// the client must expect that the underlying WebSocket connection will be closed from the server-side. +// A new connection will automatically be established to a different server. +// The correct way of handling this event is documented online: +// https://docs.coinapi.io/#reconnect-in +type Reconnect struct { + Type MessageType `json:"type"` + Within_seconds uint32 `json:"within_seconds"` + Before_time time.Time `json:"before_time"` +} + +func (s Reconnect) String() string { + return fmt.Sprintf("{Type: %v, Within_seconds: %v, Before_time: %v,}", + s.Type, + s.Within_seconds, + s.Before_time, + ) +} + +// Heartbeat message is sent to you every time there is one second of silence in communication between us, +// if you agreed on this feature in Hello message. +// https://docs.coinapi.io/#heartbeat-in +type Heartbeat struct { + Type MessageType `json:"type"` +} + +func (s Heartbeat) String() string { + return fmt.Sprintf("{Type: %v}", + s.Type, + ) +} + +// Trade message is sent for every executed transaction (orderbook match). +// https://docs.coinapi.io/#trades-in +type Trade struct { + Type MessageType `json:"type"` + Symbol_id string `json:"symbol_id"` + Sequence uint32 `json:"sequence"` + Time_exchange time.Time `json:"time_exchange"` + Time_coinapi time.Time `json:"time_coinapi"` + Uuid string `json:"uuid"` + Price decimal.Decimal `json:"price"` + Size decimal.Decimal `json:"size"` + Taker_side string `json:"taker_side"` +} + +func (s Trade) String() string { + return fmt.Sprintf(" { MessageType: %v, Symbol_id: %v, Sequence: %v, Time_exchange: %v, Time_coinapi: %v, Uuid: %v, Price: %v, Size: %v, Taker_side: %v}", + s.Type, + s.Symbol_id, + s.Sequence, + s.Time_exchange, + s.Time_coinapi, + s.Uuid, + s.Price, + s.Size, + s.Taker_side, + ) +} + +// Volume message is sent periodically to update last volume information per symbols on periods 1HRS, 1DAY and 1MTH. +// The 1HRS and 1DAY volumes are updated every minute and 1MTH every 10 minutes. +// Subscription to this message type triggers redelivery of the last published messages for each period. +// https://docs.coinapi.io/#volume-in +type Volume struct { + Type MessageType `json:"type"` + Period_id string `json:"period_id"` + Time_coinapi time.Time `json:"time_coinapi"` + Volume_by_symbol []VolumeBySymbol `json:"volume_by_symbol"` +} + +func (s Volume) String() string { + return fmt.Sprintf("{Type: %v, Period_id: %v, Time_coinapi: %v Volume_by_symbol: %v}", + s.Type, + s.Period_id, + s.Time_coinapi, + s.Volume_by_symbol, + ) +} + +// VolumeBySymbol subtype for Volume +// https://docs.coinapi.io/#volume-in +type VolumeBySymbol struct { + Symbol_id string `json:"symbol_id"` + Asset_id_base string `json:"asset_id_base"` + Asset_id_quote string `json:"asset_id_quote"` + Volume_base decimal.Decimal `json:"volume_base"` + Volume_quote decimal.Decimal `json:"volume_quote"` +} + +func (s VolumeBySymbol) String() string { + return fmt.Sprintf("{Symbol_id: %v, Asset_id_base: %v, Asset_id_quote: %v, Volume_base: %v, Volume_quote: %v, }", + s.Symbol_id, + s.Asset_id_base, + s.Asset_id_quote, + s.Volume_base, + s.Volume_quote, + ) +} diff --git a/data-api/go-ws/api/utils.go b/data-api/go-ws/api/utils.go new file mode 100644 index 0000000000..1d02a053b2 --- /dev/null +++ b/data-api/go-ws/api/utils.go @@ -0,0 +1,59 @@ +package api + +import ( + . "go-ws/api/types" + v1 "go-ws/api/v1" + "strings" +) + +func validateApiKey(apiKey string) { + + // Check if key empty + if apiKey == "" { + printErrorMessage("API key is empty!", "Add a valid API key to main!") + panic("Invalid API KEY - Abort!") + } + + // Check for test key + if strings.Contains(apiKey, "SAMPLE-KEY") || strings.Contains(apiKey, "SAMPLE") || strings.Contains(apiKey, "TEST") { + printErrorMessage("Inactive example key detected!", "Add your own valid API key to main!") + panic("Invalid API KEY - Abort!") + } + + // Check for copy & paste error. Test keys should be 36 characters long! + // It's unclear to me if key length is fixed or dynamic, thus 21 seems to be the safest option. + if len(apiKey) <= 21 { + printErrorMessage("API key is too short. Should be 30 or more characters long!", "Add a valid API key to main!") + panic("Invalid API KEY - Abort!") + } +} + +func printErrorMessage(problem, solution string) { + println() + println("Problem : ", problem) + println("Solution: ", solution) + println("Web Link: https://www.coinapi.io/pricing?apikey") + println() +} + +func getSDKConfig(apiKey string) (sdkConfig *SdkConfig) { + sdkConfig = &SdkConfig{ + ApiKey: apiKey, + ApiVersion: ApiV1, + EnvironmentType: TestInsecure, + ReconnectType: OnConnectionClose, + } + return sdkConfig +} + +func getSDK(sdkConfig *SdkConfig) (sdk SDK) { + switch sdkConfig.ApiVersion { + case ApiV1: + // Bind interface to implementation matching the selected API version. + sdk = v1.NewCoinApiSDKV1(sdkConfig) + + default: + sdk = v1.NewCoinApiSDKV1(sdkConfig) + } + return sdk +} diff --git a/data-api/go-ws/api/v1/dbg_utils.go b/data-api/go-ws/api/v1/dbg_utils.go new file mode 100644 index 0000000000..036d362b9d --- /dev/null +++ b/data-api/go-ws/api/v1/dbg_utils.go @@ -0,0 +1,16 @@ +package v1 + +import "log" + +func logError(err error) { + if err != nil { + log.Println(err) + } +} + +func checkError(err error) error { + if err != nil { + return nil + } + return err +} diff --git a/data-api/go-ws/api/v1/endpoints.go b/data-api/go-ws/api/v1/endpoints.go new file mode 100644 index 0000000000..40002d8546 --- /dev/null +++ b/data-api/go-ws/api/v1/endpoints.go @@ -0,0 +1,28 @@ +package v1 + +import t "go-ws/api/types" + +// Endpoints WebSocket endpoint provides real-time market data streaming which works in Subscribe-Publish communication model. +// https://docs.coinapi.io/#md-websocket-api +const ( + ProductionEncrypted = "wss://ws.coinapi.io/v1/" + ProductionInsecure = "ws://ws.coinapi.io/v1/" + SandboxEncrypted = "wss://ws-sandbox.coinapi.io/v1/" + SandboxInsecure = "ws://ws-sandbox.coinapi.io/v1/" +) + +func getUrl(env t.EnvironmentType) (url string) { + switch env { + case t.ProdEncrypted: + return ProductionEncrypted + case t.ProdInsecure: + return ProductionInsecure + case t.TestEncrypted: + return SandboxEncrypted + case t.TestInsecure: + return SandboxInsecure + default: + return SandboxEncrypted + } + +} diff --git a/data-api/go-ws/api/v1/sdk.go b/data-api/go-ws/api/v1/sdk.go new file mode 100644 index 0000000000..22de7a9dd7 --- /dev/null +++ b/data-api/go-ws/api/v1/sdk.go @@ -0,0 +1,42 @@ +package v1 + +import ( + "github.com/gorilla/websocket" + . "go-ws/api/types" +) + +type SDKImpl struct { + config *SdkConfig +} + +var ( + con *websocket.Conn + stopC chan struct{} + doneC chan struct{} + running bool + helloMsg *Hello +) + +var ( + // data handlers + tradesInvoke InvokeFunction + quotesInvoke InvokeFunction + bookInvoke InvokeFunction + ohlcvInvoke InvokeFunction + volumeInvoke InvokeFunction + exchangeInvoke InvokeFunction + // sys handlers + errorInvoke InvokeFunction + heartBeatInvoke InvokeFunction + reconnectInvoke InvokeFunction +) + +func NewCoinApiSDKV1(sdkConfig *SdkConfig) (sdk *SDKImpl) { + sdk = &SDKImpl{sdkConfig} + sdk.init() + return sdk +} + +func (s SDKImpl) init() { + _ = s.OpenConnection() // errors get handled inside connect() +} diff --git a/data-api/go-ws/api/v1/sdk_utils.go b/data-api/go-ws/api/v1/sdk_utils.go new file mode 100644 index 0000000000..3d59b0012d --- /dev/null +++ b/data-api/go-ws/api/v1/sdk_utils.go @@ -0,0 +1,21 @@ +package v1 + +import ( + "go-ws/api/types" + "log" +) + +func (s SDKImpl) getWSConfig() (wsCfg *types.WsConfig) { + url := getUrl(s.config.EnvironmentType) + wsCfg = &types.WsConfig{ + ApiKey: s.config.ApiKey, + Endpoint: url, + } + return wsCfg +} + +func printRawMsg(message []byte) { + msg := string(message) + log.Println("raw message: ") + log.Println(msg) +} diff --git a/data-api/go-ws/api/v1/set_methods.go b/data-api/go-ws/api/v1/set_methods.go new file mode 100644 index 0000000000..3907bddc84 --- /dev/null +++ b/data-api/go-ws/api/v1/set_methods.go @@ -0,0 +1,50 @@ +package v1 + +import ( + . "go-ws/api/types" +) + +func (s SDKImpl) SetTradesInvoke(function InvokeFunction) { + tradesInvoke = function +} + +func (s SDKImpl) SetQuoteInvoke(function InvokeFunction) { + quotesInvoke = function +} + +func (s SDKImpl) SetBookInvoke(function InvokeFunction) { + bookInvoke = function +} + +func (s SDKImpl) SetOHLCVInvoke(function InvokeFunction) { + ohlcvInvoke = function +} + +func (s SDKImpl) SetVolumeInvoke(function InvokeFunction) { + volumeInvoke = function +} + +func (s SDKImpl) SetExRateInvoke(function InvokeFunction) { + exchangeInvoke = function +} + +// sys handlers + +func (s SDKImpl) SetErrorInvoke(function InvokeFunction) { + errorInvoke = function +} + +func (s SDKImpl) SetHeartBeatInvoke(function InvokeFunction) { + heartBeatInvoke = function +} + +func (s SDKImpl) SetReconnectInvoke(function InvokeFunction) { + reconnectInvoke = function +} + +func (s SDKImpl) setHelloMessage(helloMessage *Hello) { + helloMsg = helloMessage +} +func (s SDKImpl) getHelloMessage() (helloMessage *Hello) { + return helloMsg +} diff --git a/data-api/go-ws/api/v1/websocket.go b/data-api/go-ws/api/v1/websocket.go new file mode 100644 index 0000000000..32becda53c --- /dev/null +++ b/data-api/go-ws/api/v1/websocket.go @@ -0,0 +1,88 @@ +package v1 + +import ( + "go-ws/api/types" + "log" +) + +func (s SDKImpl) SendHello(hello *types.Hello) (err error) { + + b, err := hello.GetJSON() + logError(err) + + err = con.WriteMessage(1, b) + if err != nil { + log.Println("can't send Hello message!") + logError(err) + return err + } + + // store last hello message in case of a hard re-connect. + s.setHelloMessage(hello) + + if running == false { + err = s.startProcessing() + if err != nil { + log.Println("can't start message processing!") + logError(err) + return err + } + running = true + } + return err +} + +func (s SDKImpl) startProcessing() (err error) { + errHandler := logError + handler := s.getWSHandler(errHandler) + doneC, stopC, err = s.process(handler, errHandler) + if err != nil { + log.Println("error starting message processing!") + logError(err) + running = false + return err + } + running = true + return nil +} + +func (s SDKImpl) process(handler types.WsHandler, errHandler types.WsErrHandler) (doneC, stopC chan struct{}, err error) { + + doneC = make(chan struct{}) + stopC = make(chan struct{}) + + go func() { + // This function will exit either on error from ReadMessage + // or when the stopC channel is closed by the client. + defer close(doneC) + + // Wait for the stopC channel to be closed. We do that in a + // separate goroutine because ReadMessage is a blocking operation. + silent := false + go func() { + select { + case <-stopC: + silent = true + case <-doneC: + } + _ = con.Close() + }() + + var message []byte + for { + _, message, err = con.ReadMessage() + if err != nil { + if !silent { + log.Println("Error reading message!") + errHandler(err) + } + return + } + + // + //printRawMsg(message) + handler(message) + } + }() + return +} diff --git a/data-api/go-ws/api/v1/ws_connection.go b/data-api/go-ws/api/v1/ws_connection.go new file mode 100644 index 0000000000..c68aaa3e09 --- /dev/null +++ b/data-api/go-ws/api/v1/ws_connection.go @@ -0,0 +1,54 @@ +package v1 + +import ( + "github.com/gorilla/websocket" + "log" +) + +func (s SDKImpl) OpenConnection() (err error) { + mtd := "connect: " + wsConfig := s.getWSConfig() + url := wsConfig.Endpoint + con, _, err = websocket.DefaultDialer.Dial(wsConfig.Endpoint, nil) + if err != nil { + log.Println(mtd, err) + panic(mtd + "Cannot connect to: " + url) + } + running = false + return err +} + +func (s SDKImpl) CloseConnection() (err error) { + + // Stop processing messages + running = false + + // close WS channel if its not yet fully closed! + if stopC != nil { + close(stopC) + } + + // close connection + err = con.Close() + if err != nil { + //log.Println("can't close connection") + log.Println(err) + } + return err +} + +func (s SDKImpl) ResetConnection() (err error) { + + err = s.CloseConnection() + logError(err) + + err = s.OpenConnection() + logError(err) + + hello := s.getHelloMessage() + + err = s.SendHello(hello) + logError(err) + + return err +} diff --git a/data-api/go-ws/api/v1/ws_handler.go b/data-api/go-ws/api/v1/ws_handler.go new file mode 100644 index 0000000000..af516ff2a2 --- /dev/null +++ b/data-api/go-ws/api/v1/ws_handler.go @@ -0,0 +1,163 @@ +package v1 + +import ( + "encoding/json" + "github.com/bitly/go-simplejson" + t "go-ws/api/types" +) + +func (s SDKImpl) getWSHandler(errHandler t.WsErrHandler) (wsHandler t.WsHandler) { + wsHandler = func(message []byte) { + err := s.processMessage(message, errHandler) + if err != nil { + errHandler(err) + } + } + return wsHandler +} + +func (s SDKImpl) processMessage(message []byte, errHandler t.WsErrHandler) (err error) { + + var dataMessage = new(t.DataMessage) + messageType := s.getMessageType(message, errHandler) + + switch messageType { + case t.EXCHANGERATE: + // https://docs.coinapi.io/#exchange-rate-in + msg := new(t.ExchangeRate) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage.ExchangeRate = msg + err = exchangeInvoke(dataMessage) + return checkError(err) + + case t.BOOK_L2_TOP_5: + dataMessage = s.unMarshalOrderBook(message, messageType, errHandler) + err = bookInvoke(dataMessage) + return checkError(err) + + case t.BOOK_L2_TOP_20: + dataMessage = s.unMarshalOrderBook(message, messageType, errHandler) + err = bookInvoke(dataMessage) + return checkError(err) + + case t.BOOK_L2_TOP_50: + dataMessage = s.unMarshalOrderBook(message, messageType, errHandler) + err = bookInvoke(dataMessage) + return checkError(err) + + case t.BOOK_L2_FULL: + // https://docs.coinapi.io/#orderbook-l2-full-in + dataMessage = s.unMarshalOrderBook(message, messageType, errHandler) + err = bookInvoke(dataMessage) + return checkError(err) + + case t.BOOK_L3_FULL: + // https://docs.coinapi.io/#orderbook-l3-full-in + dataMessage = s.unMarshalOrderBook(message, messageType, errHandler) + err = bookInvoke(dataMessage) + return checkError(err) + + case t.OHLCV: + // https://docs.coinapi.io/#ohlcv-in + msg := new(t.Ohlcv) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Ohlcv = msg + err = ohlcvInvoke(dataMessage) + return checkError(err) + + case t.QUOTE: + // https://docs.coinapi.io/#quotes-in + msg := new(t.Quote) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Quote = msg + err = quotesInvoke(dataMessage) + return checkError(err) + + case t.TRADE: + // https://docs.coinapi.io/#trades-in + msg := new(t.Trade) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Trade = msg + err = tradesInvoke(dataMessage) + return checkError(err) + + case t.VOLUME: + // https://docs.coinapi.io/#volume-in + msg := new(t.Volume) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Volume = msg + err = volumeInvoke(dataMessage) + return checkError(err) + + case t.ERROR: + // https://docs.coinapi.io/#error-handling + errorMsg := new(t.ErrorMessage) + _ = json.Unmarshal(message, errorMsg) + dataMessage.ErrorMessage = errorMsg + err = errorInvoke(dataMessage) + return checkError(err) + + case t.RECONNECT: + // https://docs.coinapi.io/#reconnect-in + msg := new(t.Reconnect) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Reconnect = msg + err = reconnectInvoke(dataMessage) + return checkError(err) + + case t.HEARTBEAT: + // https://docs.coinapi.io/#heartbeat-in + msg := new(t.Heartbeat) + msg.Type = messageType + _ = json.Unmarshal(message, msg) + dataMessage = new(t.DataMessage) + dataMessage.Hearbeat = msg + err = heartBeatInvoke(dataMessage) + return checkError(err) + } + + return nil +} + +func (s SDKImpl) unMarshalOrderBook(message []byte, msgType t.MessageType, errHandler t.WsErrHandler) (dataMessage *t.DataMessage) { + bookMsg := new(t.OrderBook) + bookMsg.Type = msgType + err := json.Unmarshal(message, bookMsg) + if err != nil { + errHandler(err) + return nil + } + dataMessage = new(t.DataMessage) + dataMessage.Orderbook = bookMsg + return dataMessage + +} + +func (s SDKImpl) getMessageType(message []byte, errHandler t.WsErrHandler) (messageType t.MessageType) { + j, err := newJSON(message) + if err != nil { + errHandler(err) + return + } + messageType = t.MessageType(j.Get("type").MustString()) + return messageType +} + +func newJSON(data []byte) (j *simplejson.Json, err error) { + j, err = simplejson.NewJson(data) + if err != nil { + return nil, err + } + return j, nil +} diff --git a/data-api/go-ws/go.mod b/data-api/go-ws/go.mod new file mode 100644 index 0000000000..f0dc107939 --- /dev/null +++ b/data-api/go-ws/go.mod @@ -0,0 +1,12 @@ +module go-ws + +go 1.15 + +require ( + github.com/bitly/go-simplejson v0.5.0 + github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect + github.com/gorilla/websocket v1.4.2 + github.com/kr/pretty v0.2.1 // indirect + github.com/shopspring/decimal v1.2.0 + github.com/stretchr/testify v1.7.0 // indirect +) diff --git a/data-api/go-ws/go.sum b/data-api/go-ws/go.sum new file mode 100644 index 0000000000..51221aa652 --- /dev/null +++ b/data-api/go-ws/go.sum @@ -0,0 +1,20 @@ +github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y= +github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA= +github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/data-api/go-ws/main.go b/data-api/go-ws/main.go new file mode 100644 index 0000000000..5b7f54deb2 --- /dev/null +++ b/data-api/go-ws/main.go @@ -0,0 +1,286 @@ +package main + +import ( + "errors" + "go-ws/api" + t "go-ws/api/types" + "log" + "time" +) + +const apiKey = "THIS-IS-A-SAMPLE-API-KEY-C2A7CB1EF" + +// All exchanges & data integrations: +// https://www.coinapi.io/integration + +func main() { + println(" * NewSDK!") + sdk := api.NewSDK(apiKey) + // verbose switches on / off console printing of heartbeat & reconnect messages + sys := getSysInvokes(true) + + println(" * SetErrorInvoke!") + sdk.SetErrorInvoke(sys.ErrorInvoke) + + println(" * SetHeartBeatInvoke!") + sdk.SetHeartBeatInvoke(sys.HeartBeatInvoke) + + println(" * SetReconnectInvoke!") + sdk.SetReconnectInvoke(sys.ReconnectInvoke) + + println(" * SetOHLCVInvoke!") + OHLCVInvoke := GetInvokeFunction(t.OHLCV) + sdk.SetOHLCVInvoke(OHLCVInvoke) + + println(" * SetTradesInvoke!") + tradeInvoke := GetInvokeFunction(t.TRADE) + sdk.SetTradesInvoke(tradeInvoke) + + println(" * SetQuoteInvoke!") + quoteInvoke := GetInvokeFunction(t.QUOTE) + sdk.SetQuoteInvoke(quoteInvoke) + + println(" * SetExRateInvoke!") + exRateInvoke := GetInvokeFunction(t.EXCHANGERATE) + sdk.SetExRateInvoke(exRateInvoke) + + println(" * SetBookInvoke!") + bookInvoke := GetInvokeFunction(t.BOOK_L2_FULL) + sdk.SetBookInvoke(bookInvoke) + + volInvoke := GetInvokeFunction(t.VOLUME) + sdk.SetVolumeInvoke(volInvoke) + + println(" * SendHello: Single data type!") + hello := getHello(false, false) + _ = sdk.SendHello(hello) + + println(" * Wait for messages!") + time.Sleep(time.Second * 5) + + println("******************") + println("* Hard Conn Reset *") + println("******************") + _ = sdk.ResetConnection() + + println(" * SendHello: Expanded data t!") + hello = getHello(true, false) + _ = sdk.SendHello(hello) + + println(" * Wait for messages!") + time.Sleep(time.Second * 5) + + println(" * SendHello: Heartbeat!") + hello = getHello(false, true) + _ = sdk.SendHello(hello) + + println(" * Wait for messages!") + time.Sleep(time.Second * 5) + + println(" * GetHello: Volume only!") + hello = getExchangeVolumeHello(false) + + println(" * SendHello: Requesting Volume type only !") + _ = sdk.SendHello(hello) + + println(" * Wait for messages!") + time.Sleep(time.Second * 3) + + // stop volume feed... + hello = getHello(false, false) + _ = sdk.SendHello(hello) + time.Sleep(time.Second * 1) + + println(" * CloseConnection!") + _ = sdk.CloseConnection() + + println("Goodbye!") +} + +func getExchangeVolumeHello(heartbeat bool) (hello *t.Hello) { + // For volume data, only asset ID is required. + // It seems there is no filtering so expect huge volume from all connected exchanges.. + var assets []string + var dataTypes []string + + assets = append(assets, "BTC") + dataTypes = append(dataTypes, "volume") + + hello = &t.Hello{ + Type: "hello", + Api_key: apiKey, + Heartbeat: heartbeat, + Subscribe_data_type: dataTypes, + Subscribe_filter_asset_id: assets, + } + return hello +} + +func getHello(expanded, heartbeat bool) (hello *t.Hello) { + // After your WebSocket connection is established, you must send us a Hello message which contains: + // * Stream preferences (Heartbeat and subscription details) + // * API key for authorization + // If your message will be incorrect, we will send you error message and disconnect connection afterwards. + // Hello message can be repeated, each one will cause subscription scope override without interruption + // of your WebSocket connection. + // https://docs.coinapi.io/#hello-out + + var datat []string + var symbolIds []string + var periodIDs []string + + datat = append(datat, "ohlcv") + if expanded { + datat = append(datat, "trade") + datat = append(datat, "quote") + datat = append(datat, "exrate") + datat = append(datat, "book5") + + } + + symbolIds = append(symbolIds, "COINBASE_SPOT_BTC_USD") + periodIDs = append(periodIDs, "1MIN") + + hello = &t.Hello{ + Type: "hello", + Api_key: apiKey, + Heartbeat: heartbeat, + Subscribe_data_type: datat, + Subscribe_filter_period_id: periodIDs, + Subscribe_filter_symbol_id: symbolIds, + } + return hello +} + +type SysInvokes struct { + ErrorInvoke t.InvokeFunction + HeartBeatInvoke t.InvokeFunction + ReconnectInvoke t.InvokeFunction +} + +func getSysInvokes(verbose bool) SysInvokes { + errorInvoke := GetErrorInvoke() + heartBeatInvoke := GetHeartBeatInvoke(verbose) + reconnectInvoke := GetReconnectInvoke(verbose) + + return SysInvokes{ + ErrorInvoke: errorInvoke, + HeartBeatInvoke: heartBeatInvoke, + ReconnectInvoke: reconnectInvoke, + } +} + +func GetReconnectInvoke(verbose bool) t.InvokeFunction { + // Reconnect message is sent by the server to all connected clients when the server will be restarted + // or shut down at the defined exact time included in the message content. + // After the period specified in message passes, the client must expect that the + // underlying WebSocket connection will be closed from the server-side. + // A new connection will automatically be established to a different server. + // The correct way of handling this event depends on the specific requirements of the integration... + // https://docs.coinapi.io/#reconnect-in + return func(message *t.DataMessage) (err error) { + + //sec := message.Reconnect.Within_seconds + //before := message.Reconnect.Before_time + + if verbose { + log.Println() + log.Println("!!!!!!!!!!!!!!!!!") + log.Println("!!!!Reconnect!!!! ") + log.Println("!!!!!!!!!!!!!!!!!") + log.Println() + } + + return nil + } +} + +func GetHeartBeatInvoke(verbose bool) t.InvokeFunction { + // WebSocket working on TCP protocol which doesn’t have the feature indicating that the connection is broken without + // trying exchange data over it. As you will not be actively sending messages to us, + // with Heartbeat you can distinguish a situation where there are no market data updates + // for you (Heartbeat is delivered but no market data updates) + // or connection between us is broken (Heartbeat and market data updates are not delivered). + // https://docs.coinapi.io/#reconnect-in + return func(message *t.DataMessage) (err error) { + if verbose { + log.Println() + log.Println("===============================") + log.Println("= Tracking heartbeat message! =") + log.Println("===============================") + log.Println() + } + return nil + } +} + +func GetErrorInvoke() t.InvokeFunction { + // You need to be prepared to receive an error message from us when you send something wrong; + // all errors are permanent and you should expect that the underlying + // WebSocket connection will be closed by us after sending an error message. + // Good practice is to store all error messages somewhere for further manual review. + // https://docs.coinapi.io/#error-handling + return func(message *t.DataMessage) (err error) { + mtd := "ErrorHandler: " + println(mtd) + msg := message.ErrorMessage.Message + if msg != "" { + log.Println(mtd+"ErrorMessage: ", msg) + return errors.New(msg) + } + return nil + } +} + +func GetInvokeFunction(msgType t.MessageType) t.InvokeFunction { + return func(message *t.DataMessage) (err error) { + printMessage(msgType, message) + return nil + } +} + +func printMessage(msgType t.MessageType, message *t.DataMessage) { + switch msgType { + case t.ERROR: + msg := message.ErrorMessage + log.Println(msg) + println() + case t.EXCHANGERATE: + msg := message.ExchangeRate + log.Println(msg) + println() + case t.BOOK_L2_TOP_5: + printBook(message) + case t.BOOK_L2_TOP_20: + printBook(message) + case t.BOOK_L2_TOP_50: + printBook(message) + case t.BOOK_L2_FULL: + printBook(message) + case t.BOOK_L3_FULL: + printBook(message) + case t.OHLCV: + msg := message.Ohlcv + log.Println(msg) + println() + case t.QUOTE: + msg := message.Quote + log.Println(msg) + println() + case t.TRADE: + msg := message.Trade + log.Println(msg) + println() + case t.VOLUME: + msg := message.Volume + log.Println(msg) + println() + + } +} + +func printBook(message *t.DataMessage) { + msg := message.Orderbook + log.Println(msg) + println() +} diff --git a/haskell-rest/.gitignore b/data-api/haskell-rest/.gitignore similarity index 100% rename from haskell-rest/.gitignore rename to data-api/haskell-rest/.gitignore diff --git a/haskell-rest/CoinApi.hs b/data-api/haskell-rest/CoinApi.hs similarity index 88% rename from haskell-rest/CoinApi.hs rename to data-api/haskell-rest/CoinApi.hs index e296f2a1e2..cecad20e0f 100644 --- a/haskell-rest/CoinApi.hs +++ b/data-api/haskell-rest/CoinApi.hs @@ -39,13 +39,7 @@ module CoinApi (ApiKey (..) ,orderbooks_historical_data ,orderbooks_historical_data_e ,orderbooks_historical_data_l - ,orderbooks_historical_data_el - ,twitter_latest_data - ,twitter_latest_data_l - ,twitter_historical_data - ,twitter_historical_data_e - ,twitter_historical_data_l - ,twitter_historical_data_el) where + ,orderbooks_historical_data_el) where import Debug.Trace @@ -81,9 +75,6 @@ import qualified CoinApi.Types.Symbol as Symbol import CoinApi.Types.Trade (Trade) import qualified CoinApi.Types.Trade as Trade -import CoinApi.Types.Tweet (Tweet) -import qualified CoinApi.Types.Tweet as Tweet - ---- import Data.Aeson @@ -309,27 +300,3 @@ orderbooks_historical_data_el apiKey symbol_id time_start time_end limit = reque "&time_end=" ++ showTime time_end ++ "&limit=" ++ show limit) -twitter_latest_data :: MonadIO m => ApiKey -> m (Either String [Tweet]) -twitter_latest_data apiKey = request apiKey "/v1/twitter/latest" - -twitter_latest_data_l :: MonadIO m => ApiKey -> Int -> m (Either String [Tweet]) -twitter_latest_data_l apiKey limit = request apiKey ("/v1/twitter/latest?limit=" ++ show limit) - -twitter_historical_data :: MonadIO m => ApiKey -> UTCTime -> m (Either String [Tweet]) -twitter_historical_data apiKey time_start = request apiKey ("/v1/twitter/history?time_start=" ++ showTime time_start) - -twitter_historical_data_e :: MonadIO m => ApiKey -> UTCTime -> UTCTime -> m (Either String [Tweet]) -twitter_historical_data_e apiKey time_start time_end = request apiKey ("/v1/twitter/history?time_start=" ++ - showTime time_start ++ - "&time_end=" ++ showTime time_end) - -twitter_historical_data_l :: MonadIO m => ApiKey -> UTCTime -> Int -> m (Either String [Tweet]) -twitter_historical_data_l apiKey time_start limit = request apiKey ("/v1/twitter/history" ++ - "?time_start=" ++ showTime time_start ++ - "&limit=" ++ show limit) - -twitter_historical_data_el :: MonadIO m => ApiKey -> UTCTime -> UTCTime -> Int -> m (Either String [Tweet]) -twitter_historical_data_el apiKey time_start time_end limit = request apiKey ("/v1/twitter/history" ++ - "?time_start=" ++ showTime time_start ++ - "&time_end=" ++ showTime time_end ++ - "&limit=" ++ show limit) diff --git a/haskell-rest/CoinApi/Monadic.hs b/data-api/haskell-rest/CoinApi/Monadic.hs similarity index 88% rename from haskell-rest/CoinApi/Monadic.hs rename to data-api/haskell-rest/CoinApi/Monadic.hs index 26df3efad9..01ad605997 100644 --- a/haskell-rest/CoinApi/Monadic.hs +++ b/data-api/haskell-rest/CoinApi/Monadic.hs @@ -31,9 +31,6 @@ import qualified CoinApi.Types.Symbol as Symbol import CoinApi.Types.Trade (Trade) import qualified CoinApi.Types.Trade as Trade -import CoinApi.Types.Tweet (Tweet) -import qualified CoinApi.Types.Tweet as Tweet - ---- import CoinApi as CA @@ -162,21 +159,3 @@ orderbooks_historical_data_l symbol_id time_start limit = get >>= (\key -> CA.or orderbooks_historical_data_el :: MonadIO m => String -> UTCTime -> UTCTime -> Int -> CoinApi m (Either String [Orderbook]) orderbooks_historical_data_el symbol_id time_start time_end limit = get >>= (\key -> CA.orderbooks_historical_data_el key symbol_id time_start time_end limit) - -twitter_latest_data :: MonadIO m => CoinApi m (Either String [Tweet]) -twitter_latest_data = get >>= CA.twitter_latest_data - -twitter_latest_data_l :: MonadIO m => Int -> CoinApi m (Either String [Tweet]) -twitter_latest_data_l limit = get >>= (\key -> CA.twitter_latest_data_l key limit) - -twitter_historical_data :: MonadIO m => UTCTime -> CoinApi m (Either String [Tweet]) -twitter_historical_data time_start = get >>= (\key -> CA.twitter_historical_data key time_start) - -twitter_historical_data_e :: MonadIO m => UTCTime -> UTCTime -> CoinApi m (Either String [Tweet]) -twitter_historical_data_e time_start time_end = get >>= (\key -> CA.twitter_historical_data_e key time_start time_end) - -twitter_historical_data_l :: MonadIO m => UTCTime -> Int -> CoinApi m (Either String [Tweet]) -twitter_historical_data_l time_start limit = get >>= (\key -> CA.twitter_historical_data_l key time_start limit) - -twitter_historical_data_el :: MonadIO m => UTCTime -> UTCTime -> Int -> CoinApi m (Either String [Tweet]) -twitter_historical_data_el time_start time_end limit = get >>= (\key -> CA.twitter_historical_data_el key time_start time_end limit) diff --git a/haskell-rest/CoinApi/Types/Asset.hs b/data-api/haskell-rest/CoinApi/Types/Asset.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Asset.hs rename to data-api/haskell-rest/CoinApi/Types/Asset.hs diff --git a/haskell-rest/CoinApi/Types/Exchange.hs b/data-api/haskell-rest/CoinApi/Types/Exchange.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Exchange.hs rename to data-api/haskell-rest/CoinApi/Types/Exchange.hs diff --git a/haskell-rest/CoinApi/Types/Internal.hs b/data-api/haskell-rest/CoinApi/Types/Internal.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Internal.hs rename to data-api/haskell-rest/CoinApi/Types/Internal.hs diff --git a/haskell-rest/CoinApi/Types/Message.hs b/data-api/haskell-rest/CoinApi/Types/Message.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Message.hs rename to data-api/haskell-rest/CoinApi/Types/Message.hs diff --git a/haskell-rest/CoinApi/Types/OHLCV.hs b/data-api/haskell-rest/CoinApi/Types/OHLCV.hs similarity index 100% rename from haskell-rest/CoinApi/Types/OHLCV.hs rename to data-api/haskell-rest/CoinApi/Types/OHLCV.hs diff --git a/haskell-rest/CoinApi/Types/Orderbook.hs b/data-api/haskell-rest/CoinApi/Types/Orderbook.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Orderbook.hs rename to data-api/haskell-rest/CoinApi/Types/Orderbook.hs diff --git a/haskell-rest/CoinApi/Types/Period.hs b/data-api/haskell-rest/CoinApi/Types/Period.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Period.hs rename to data-api/haskell-rest/CoinApi/Types/Period.hs diff --git a/haskell-rest/CoinApi/Types/Quote.hs b/data-api/haskell-rest/CoinApi/Types/Quote.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Quote.hs rename to data-api/haskell-rest/CoinApi/Types/Quote.hs diff --git a/haskell-rest/CoinApi/Types/Rate.hs b/data-api/haskell-rest/CoinApi/Types/Rate.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Rate.hs rename to data-api/haskell-rest/CoinApi/Types/Rate.hs diff --git a/haskell-rest/CoinApi/Types/Symbol.hs b/data-api/haskell-rest/CoinApi/Types/Symbol.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Symbol.hs rename to data-api/haskell-rest/CoinApi/Types/Symbol.hs diff --git a/haskell-rest/CoinApi/Types/Trade.hs b/data-api/haskell-rest/CoinApi/Types/Trade.hs similarity index 100% rename from haskell-rest/CoinApi/Types/Trade.hs rename to data-api/haskell-rest/CoinApi/Types/Trade.hs diff --git a/haskell-rest/LICENSE b/data-api/haskell-rest/LICENSE similarity index 100% rename from haskell-rest/LICENSE rename to data-api/haskell-rest/LICENSE diff --git a/haskell-rest/Main.hs b/data-api/haskell-rest/Main.hs similarity index 80% rename from haskell-rest/Main.hs rename to data-api/haskell-rest/Main.hs index fbe43fd4e5..455983bd9d 100644 --- a/haskell-rest/Main.hs +++ b/data-api/haskell-rest/Main.hs @@ -180,48 +180,6 @@ pure = do Left err -> putStrLn err putStrLn "" - putStrLn "twitter_latest_data:" - ex <- twitter_latest_data key - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - putStrLn "twitter_latest_data_l:" - ex <- twitter_latest_data_l key limit - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - putStrLn "twitter_historical_data:" - ex <- twitter_historical_data key time_start - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - putStrLn "twitter_historical_data_e:" - ex <- twitter_historical_data_e key time_start time_end - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - putStrLn "twitter_historical_data_l:" - ex <- twitter_historical_data_l key time_start limit - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - putStrLn "twitter_historical_data_el:" - ex <- twitter_historical_data_el key time_start time_end limit - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - -- using monadic interface monadic :: IO () monadic = M.withApiKey key $ do @@ -386,48 +344,6 @@ monadic = M.withApiKey key $ do Left err -> putStrLn err putStrLn "" - ex <- M.twitter_latest_data - liftIO $ do putStrLn "twitter_latest_data:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - ex <- M.twitter_latest_data_l limit - liftIO $ do putStrLn "twitter_latest_data_l:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - ex <- M.twitter_historical_data time_start - liftIO $ do putStrLn "twitter_historical_data:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - ex <- M.twitter_historical_data_e time_start time_end - liftIO $ do putStrLn "twitter_historical_data_e:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - ex <- M.twitter_historical_data_l time_start limit - liftIO $ do putStrLn "twitter_historical_data_l:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - - ex <- M.twitter_historical_data_el time_start time_end limit - liftIO $ do putStrLn "twitter_historical_data_el:" - case ex of - Right result -> mapM_ print $ take 2 result - Left err -> putStrLn err - putStrLn "" - main = do putStrLn "Pure interface:" Main.pure putStrLn "Monadic interface:" diff --git a/haskell-rest/README.md b/data-api/haskell-rest/README.md similarity index 100% rename from haskell-rest/README.md rename to data-api/haskell-rest/README.md diff --git a/haskell-rest/Setup.hs b/data-api/haskell-rest/Setup.hs similarity index 100% rename from haskell-rest/Setup.hs rename to data-api/haskell-rest/Setup.hs diff --git a/haskell-rest/haskell-rest.cabal b/data-api/haskell-rest/haskell-rest.cabal similarity index 98% rename from haskell-rest/haskell-rest.cabal rename to data-api/haskell-rest/haskell-rest.cabal index e4217f7461..4d514c4b53 100644 --- a/haskell-rest/haskell-rest.cabal +++ b/data-api/haskell-rest/haskell-rest.cabal @@ -15,7 +15,7 @@ cabal-version: >=1.10 library exposed-modules: CoinApi, CoinApi.Monadic, CoinApi.Types.Asset, CoinApi.Types.Exchange, CoinApi.Types.OHLCV, CoinApi.Types.Orderbook, - CoinApi.Types.Period, CoinApi.Types.Quote, CoinApi.Types.Rate, CoinApi.Types.Symbol, CoinApi.Types.Trade, CoinApi.Types.Tweet + CoinApi.Types.Period, CoinApi.Types.Quote, CoinApi.Types.Rate, CoinApi.Types.Symbol, CoinApi.Types.Trade -- other-modules: -- other-extensions: build-depends: base >=4.9 && <4.10, http-conduit >= 2.2, http-types >= 0.9, aeson >= 1.1, bytestring >= 0.10, case-insensitive >= 1.2, text >= 1.2, time >= 1.6, scientific >= 0.3, vector >= 0.11, mtl >= 2.2 diff --git a/data-api/java-rest-deprecated/README.md b/data-api/java-rest-deprecated/README.md new file mode 100644 index 0000000000..6fda05df80 --- /dev/null +++ b/data-api/java-rest-deprecated/README.md @@ -0,0 +1 @@ +Please use the /java-rest-v2/ directory instead of this for new projects as this version is deprecating. diff --git a/data-api/java-rest-deprecated/README.me b/data-api/java-rest-deprecated/README.me new file mode 100644 index 0000000000..6fda05df80 --- /dev/null +++ b/data-api/java-rest-deprecated/README.me @@ -0,0 +1 @@ +Please use the /java-rest-v2/ directory instead of this for new projects as this version is deprecating. diff --git a/java-rest/compile.bat b/data-api/java-rest-deprecated/compile.bat similarity index 100% rename from java-rest/compile.bat rename to data-api/java-rest-deprecated/compile.bat diff --git a/data-api/java-rest-deprecated/java_rest_coin_api.java b/data-api/java-rest-deprecated/java_rest_coin_api.java new file mode 100644 index 0000000000..cc730f3382 --- /dev/null +++ b/data-api/java-rest-deprecated/java_rest_coin_api.java @@ -0,0 +1,1451 @@ +import okhttp3.*; +import okio.*; +import java.io.*; +import java.util.*; +import org.json.*; +import java.sql.Timestamp; + +public class java_rest_coin_api { + + public class exception extends Exception { + int code; + + public exception(int code, String message) { + super(message); + this.code = code; + } + + public int get_code() { + return code; + } + } + + public static class asset { + private String asset_id; // Our asset identifier. Superset of the ISO 4217 currency codes standard + private String name; // Display name of the asset + private boolean type_is_crypto; // true for cryptocurrency assets, false otherwise + + public asset(String asset_id, String name, boolean type_is_crypto) { + this.asset_id = asset_id; + this.name = name; + this.type_is_crypto = type_is_crypto; + } + + public String get_asset_id() { + return asset_id; + } + + public String get_name() { + return name; + } + + public boolean is_type_crypto() { + return type_is_crypto; + } + } + + public static class exchange { + private String exchange_id; // Our exchange identifier + private String name; // Display name of the exchange + private String website; // Exchange website address + + public exchange(String exchange_id, String name, String website) { + this.exchange_id = exchange_id; + this.name = name; + this.website = website; + } + + public String get_exchange_id() { + return exchange_id; + } + + public String get_name() { + return name; + } + + public String get_website() { + return website; + } + } + + public enum SYMBOL_TYPE { + INVALID, // Reserverd value for invalid data + SPOT, // FX Spot. Agreement to exchange one asset for another one (e.g. Buy BTC for USD) + FUTURES, // Futures contract. FX Spot derivative contract where traders agree to trade fx spot at predetermined future time + OPTION // Option contract. FX Spot derivative contract where traders agree to trade right to require buy or sell of fx spot at agreed price on exercise date + } + + public enum OPTION_EXERCISE_STYLE { + INVALID, + AMERICAN, + EUROPEAN + } + + public static class symbol { + private String symbol_id; // Our symbol identifier, see table below for format description. + private String exchange_id; // Our identifier of the exchange where symbol is traded. + private SYMBOL_TYPE symbol_type; // Type of symbol (possible values are: SPOT, FUTURES or OPTION) + private String asset_id_base; // FX Spot base asset identifier, for derivatives it's contact underlying (e.g. BTC for BTC/USD) + private String asset_id_quote; // FX Spot quote asset identifier, for derivatives it's contract underlying (e.g. USD for BTC/USD) + private boolean option_type_is_call; // Boolean value representing option type. true for Call options, false for Put options + private double option_strike_price; // Price at which option contract can be exercised + private double option_contract_unit; // Base asset amount of underlying spot which single option represents + private OPTION_EXERCISE_STYLE option_exercise_style; // Option exercise style. Can be EUROPEAN or AMERICAN + private Timestamp option_expiration_time; // Option contract expiration time in ISO 8601 + private Timestamp future_delivery_time; // Predetermined time of futures contract delivery date in ISO 8601 + + public symbol(String symbol_id, String exchange_id, SYMBOL_TYPE symbol_type, String asset_id_base, String asset_id_quote, + boolean option_type_is_call, double option_strike_price, double option_contract_unit, OPTION_EXERCISE_STYLE option_exercise_style, + Timestamp option_expiration_time, Timestamp future_delivery_time) { + + this.symbol_id = symbol_id; + this.exchange_id = exchange_id; + this.symbol_type = symbol_type; + this.asset_id_base = asset_id_base; + this.asset_id_quote = asset_id_quote; + this.option_type_is_call = option_type_is_call; + this.option_strike_price = option_strike_price; + this.option_contract_unit = option_contract_unit; + this.option_exercise_style = option_exercise_style; + this.option_expiration_time = option_expiration_time; + this.future_delivery_time = future_delivery_time; + } + + public symbol(String symbol_id, String exchange_id, SYMBOL_TYPE symbol_type, String asset_id_base, String asset_id_quote) { + this.symbol_id = symbol_id; + this.exchange_id = exchange_id; + this.symbol_type = symbol_type; + this.asset_id_base = asset_id_base; + this.asset_id_quote = asset_id_quote; + this.option_type_is_call = false; + this.option_strike_price = 0.0; + this.option_contract_unit = 0.0; + this.option_exercise_style = OPTION_EXERCISE_STYLE.INVALID; + this.option_expiration_time = null; + this.future_delivery_time = null; + } + + public String get_symbol_id() { + return symbol_id; + } + + public String get_exchange_id() { + return exchange_id; + } + + public SYMBOL_TYPE get_symbol_type() { + return symbol_type; + } + + public String get_asset_id_base() { + return asset_id_base; + } + + public String get_asset_id_quote() { + return asset_id_quote; + } + + public boolean get_option_type_is_call() { + return option_type_is_call; + } + + public double get_option_strike_price() { + return option_strike_price; + } + + public double get_option_contract_unit() { + return option_contract_unit; + } + + public OPTION_EXERCISE_STYLE get_option_exercise_style() { + return option_exercise_style; + } + + public Timestamp get_option_expiration_time() { + return option_expiration_time; + } + + public Timestamp get_future_delivery_time() { + return future_delivery_time; + } + } + + public static class exchange_rate { + private Timestamp time; // Time in ISO 8601 of the market data used to calculate exchange rate + private String asset_id_base; // Exchange rate base asset identifier + private String asset_id_quote; // Exchange rate quote asset identifier + private double rate; // Exchange rate between assets + + public exchange_rate(Timestamp time, String asset_id_base, String asset_id_quote, double rate) { + this.time = time; + this.asset_id_base = asset_id_base; + this.asset_id_quote = asset_id_quote; + this.rate = rate; + } + + public Timestamp get_time() { + return time; + } + + public String get_asset_id_base() { + return asset_id_base; + } + + public String get_asset_id_quote() { + return asset_id_quote; + } + + public double get_rate() { + return rate; + } + } + + enum PERIOD_IDENTIFIER { + INVALID, + _1SEC, + _2SEC, + _3SEC, + _4SEC, + _5SEC, + _6SEC, + _10SEC, + _15SEC, + _20SEC, + _30SEC, + _1MIN, + _2MIN, + _3MIN, + _4MIN, + _5MIN, + _6MIN, + _10MIN, + _15MIN, + _20MIN, + _30MIN, + _1HRS, + _2HRS, + _3HRS, + _4HRS, + _6HRS, + _8HRS, + _12HRS, + _1DAY, + _2DAY, + _3DAY, + _5DAY, + _7DAY, + _10DAY, + _1MTH, + _2MTH, + _3MTH, + _4MTH, + _6MTH, + _1YRS, + _2YRS, + _3YRS, + _4YRS, + _5YRS + } + + public static class period { + private PERIOD_IDENTIFIER period_id; // Period identifier, used in other API calls + private int length_seconds; // Seconds part of period length + private int length_months; // Months part of period length + private int unit_count; // Period length in units + private String unit_name; // Type of unit (second/minute/hour/day/month/year) + private String display_name; // Display name of period length + + public period(PERIOD_IDENTIFIER period_id, int length_seconds, int length_months, int unit_count, + String unit_name, String display_name) { + this.period_id = period_id; + this.length_seconds = length_seconds; + this.length_months = length_months; + this.unit_count = unit_count; + this.unit_name = unit_name; + this.display_name = display_name; + } + + public PERIOD_IDENTIFIER get_period_id() { + return period_id; + } + + public int get_length_seconds() { + return length_seconds; + } + + public int get_length_months() { + return length_months; + } + + public int get_unit_count() { + return unit_count; + } + + public String get_unit_name() { + return unit_name; + } + + public String get_display_name() { + return display_name; + } + } + + public static class timedata { + private Timestamp time_period_start; // Period starting time (range left inclusive) + private Timestamp time_period_end; // Period ending time (range right exclusive) + private Timestamp time_open; // Time of first trade inside period range + private Timestamp time_close; // Time of last trade inside period range + private double price_open; // First trade price inside period range + private double price_high; // Highest traded price inside period range + private double price_low; // Lowest traded price inside period range + private double price_close; // Last trade price inside period range + private double volume_traded; // Cumulative base amount traded inside period range + private int trades_count; // Amount of trades executed inside period range + + public timedata(Timestamp time_period_start, Timestamp time_period_end, Timestamp time_open, Timestamp time_close, + double price_open, double price_high, double price_low, double price_close, double volume_traded, int trades_count) { + this.time_period_start = time_period_start; + this.time_period_end = time_period_end; + this.time_open = time_open; + this.time_close = time_close; + this.price_open = price_open; + this.price_high = price_high; + this.price_low = price_low; + this.price_close = price_close; + this.volume_traded = volume_traded; + this.trades_count = trades_count; + } + + public Timestamp get_time_period_start() { + return time_period_start; + } + + public Timestamp get_time_period_end() { + return time_period_end; + } + + public Timestamp get_time_open() { + return time_open; + } + + public Timestamp get_time_close() { + return time_close; + } + + public double get_price_open() { + return price_open; + } + + public double get_price_high() { + return price_high; + } + + public double get_price_low() { + return price_low; + } + + public double get_price_close() { + return price_close; + } + + public double get_volume_traded() { + return volume_traded; + } + + public int get_trades_count() { + return trades_count; + } + } + + private static PERIOD_IDENTIFIER period_identifier_from_string(String period_id) { + if (period_id.equals("1SEC")) + return PERIOD_IDENTIFIER._1SEC; + if (period_id.equals("3SEC")) + return PERIOD_IDENTIFIER._2SEC; + if (period_id.equals("4SEC")) + return PERIOD_IDENTIFIER._3SEC; + if (period_id.equals("4SEC")) + return PERIOD_IDENTIFIER._4SEC; + if (period_id.equals("5SEC")) + return PERIOD_IDENTIFIER._5SEC; + if (period_id.equals("6SEC")) + return PERIOD_IDENTIFIER._6SEC; + if (period_id.equals("10SEC")) + return PERIOD_IDENTIFIER._10SEC; + if (period_id.equals("15SEC")) + return PERIOD_IDENTIFIER._15SEC; + if (period_id.equals("20SEC")) + return PERIOD_IDENTIFIER._20SEC; + if (period_id.equals("30SEC")) + return PERIOD_IDENTIFIER._30SEC; + if (period_id.equals("1MIN")) + return PERIOD_IDENTIFIER._1MIN; + if (period_id.equals("2MIN")) + return PERIOD_IDENTIFIER._2MIN; + if (period_id.equals("3MIN")) + return PERIOD_IDENTIFIER._3MIN; + if (period_id.equals("4MIN")) + return PERIOD_IDENTIFIER._4MIN; + if (period_id.equals("5MIN")) + return PERIOD_IDENTIFIER._5MIN; + if (period_id.equals("6MIN")) + return PERIOD_IDENTIFIER._6MIN; + if (period_id.equals("10MIN")) + return PERIOD_IDENTIFIER._10MIN; + if (period_id.equals("15MIN")) + return PERIOD_IDENTIFIER._15MIN; + if (period_id.equals("20MIN")) + return PERIOD_IDENTIFIER._20MIN; + if (period_id.equals("30MIN")) + return PERIOD_IDENTIFIER._30MIN; + if (period_id.equals("1HRS")) + return PERIOD_IDENTIFIER._1HRS; + if (period_id.equals("2HRS")) + return PERIOD_IDENTIFIER._2HRS; + if (period_id.equals("3HRS")) + return PERIOD_IDENTIFIER._3HRS; + if (period_id.equals("4HRS")) + return PERIOD_IDENTIFIER._4HRS; + if (period_id.equals("6HRS")) + return PERIOD_IDENTIFIER._6HRS; + if (period_id.equals("8HRS")) + return PERIOD_IDENTIFIER._8HRS; + if (period_id.equals("12HRS")) + return PERIOD_IDENTIFIER._12HRS; + if (period_id.equals("1DAY")) + return PERIOD_IDENTIFIER._1DAY; + if (period_id.equals("2DAY")) + return PERIOD_IDENTIFIER._2DAY; + if (period_id.equals("3DAY")) + return PERIOD_IDENTIFIER._3DAY; + if (period_id.equals("5DAY")) + return PERIOD_IDENTIFIER._5DAY; + if (period_id.equals("7DAY")) + return PERIOD_IDENTIFIER._7DAY; + if (period_id.equals("10DAY")) + return PERIOD_IDENTIFIER._10DAY; + if (period_id.equals("1MTH")) + return PERIOD_IDENTIFIER._1MTH; + if (period_id.equals("2MTH")) + return PERIOD_IDENTIFIER._2MTH; + if (period_id.equals("3MTH")) + return PERIOD_IDENTIFIER._3MTH; + if (period_id.equals("4MTH")) + return PERIOD_IDENTIFIER._4MTH; + if (period_id.equals("6MTH")) + return PERIOD_IDENTIFIER._6MTH; + if (period_id.equals("1YRS")) + return PERIOD_IDENTIFIER._1YRS; + if (period_id.equals("2YRS")) + return PERIOD_IDENTIFIER._2YRS; + if (period_id.equals("3YRS")) + return PERIOD_IDENTIFIER._3YRS; + if (period_id.equals("4YRS")) + return PERIOD_IDENTIFIER._4YRS; + if (period_id.equals("5YRS")) + return PERIOD_IDENTIFIER._5YRS; + return PERIOD_IDENTIFIER.INVALID; + } + + private static String period_id_to_string(PERIOD_IDENTIFIER period_id) { + switch(period_id) { + case _1SEC: + return "1SEC"; + case _2SEC: + return "2SEC"; + case _3SEC: + return "3SEC"; + case _4SEC: + return "4SEC"; + case _5SEC: + return "5SEC"; + case _6SEC: + return "6SEC"; + case _10SEC: + return "10SEC"; + case _15SEC: + return "15SEC"; + case _20SEC: + return "20SEC"; + case _30SEC: + return "30SEC"; + case _1MIN: + return "1MIN"; + case _2MIN: + return "2MIN"; + case _3MIN: + return "3MIN"; + case _4MIN: + return "4MIN"; + case _5MIN: + return "5MIN"; + case _6MIN: + return "6MIN"; + case _10MIN: + return "10MIN"; + case _15MIN: + return "15MIN"; + case _20MIN: + return "20MIN"; + case _30MIN: + return "30MIN"; + case _1HRS: + return "1HRS"; + case _2HRS: + return "2HRS"; + case _3HRS: + return "3HRS"; + case _4HRS: + return "4HRS"; + case _6HRS: + return "6HRS"; + case _8HRS: + return "8HRS"; + case _12HRS: + return "12HRS"; + case _1DAY: + return "1DAY"; + case _2DAY: + return "2DAY"; + case _3DAY: + return "3DAY"; + case _5DAY: + return "5DAY"; + case _7DAY: + return "7DAY"; + case _10DAY: + return "10DAY"; + case _1MTH: + return "1MTH"; + case _2MTH: + return "2MTH"; + case _3MTH: + return "3MTH"; + case _4MTH: + return "4MTH"; + case _6MTH: + return "6MTH"; + case _1YRS: + return "1YRS"; + case _2YRS: + return "2YRS"; + case _3YRS: + return "3YRS"; + case _4YRS: + return "3YRS"; + case _5YRS: + return "5YRS"; + default: + return "INVALID"; + } + } + + public enum TRADE_SIDE { + INVALID, + BUY, + SELL, + BUY_ESTIMATED, + SELL_ESTIMATED, + UNKNOWN + } + + private TRADE_SIDE taker_size_from_string(String taker_side) { + if (taker_side.equals("BUY")) + return TRADE_SIDE.BUY; + if (taker_side.equals("SELL")) + return TRADE_SIDE.SELL; + if (taker_side.equals("BUY_ESTIMATED")) + return TRADE_SIDE.BUY_ESTIMATED; + if (taker_side.equals("SELL_ESTIMATED")) + return TRADE_SIDE.SELL_ESTIMATED; + if (taker_side.equals("UNKNOWN")) + return TRADE_SIDE.UNKNOWN; + return TRADE_SIDE.INVALID; + } + + public static class trade { + private String symbol_id; // Our symbol identifier + private Timestamp time_exchange; // Time of trade reported by exchange + private Timestamp time_coinapi; // Time when coinapi first received trade from exchange + private String uuid; // Our trade unique identifier in form of UUIDv4 + private double price; // Price of the transaction + private double size; // Base asset amount traded in the transaction + private TRADE_SIDE taker_side; // Aggressor side of the transaction (BUY/SELL/BUY_ESTIMATED/SELL_ESTIMATED/UNKNOWN) + + public trade(String symbol_id, Timestamp time_exchange, Timestamp time_coinapi, String uuid, double price, double size, TRADE_SIDE taker_side) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.uuid = uuid; + this.price = price; + this.size = size; + this.taker_side = taker_side; + } + + public String get_symbol_id() { + return symbol_id; + } + + public Timestamp get_time_exchange() { + return time_exchange; + } + + public Timestamp get_time_coinapi() { + return time_coinapi; + } + + public String get_uuid() { + return uuid; + } + + public double get_price() { + return price; + } + + public double get_size() { + return size; + } + + public TRADE_SIDE get_taker_side() { + return taker_side; + } + } + + public static class quote { + private String symbol_id; // Our symbol identifier + private Timestamp time_exchange; // Exchange time of orderbook + private Timestamp time_coinapi; // CoinAPI time when orderbook received from exchange + private double ask_price; // Best asking price + private double ask_size; // Volume resting on best ask + private double bid_price; // Best bidding price + private double bid_size; // Volume resting on best bid + + public quote(String symbol_id, Timestamp time_exchange, Timestamp time_coinapi, double ask_price, double ask_size, double bid_price, double bid_size) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.ask_price = ask_price; + this.ask_size = ask_size; + this.bid_price = bid_price; + this.bid_size = bid_size; + } + + public String get_symbol_id() { + return symbol_id; + } + + public Timestamp get_time_exchange() { + return time_exchange; + } + + public Timestamp get_time_coinapi() { + return time_coinapi; + } + + public double get_ask_price() { + return ask_price; + } + + public double get_ask_size() { + return ask_size; + } + + public double get_bid_price() { + return bid_price; + } + + public double get_bid_size() { + return bid_size; + } + + public boolean has_last_trade() { + return false; + } + } + + public static class quote_with_trade extends quote { + private trade last_trade; // Last executed transaction + + public quote_with_trade(String symbol_id, Timestamp time_exchange, Timestamp time_coinapi, + double ask_price, double ask_size, double bid_price, double bid_size, trade last_trade) { + super(symbol_id, time_exchange, time_coinapi, ask_price, ask_size, bid_price, bid_size); + this.last_trade = last_trade; + } + + @Override + public boolean has_last_trade() { + return last_trade != null; + } + + public trade get_last_trade() { + return last_trade; + } + } + + public static class level { + private double price; // Price of bid/ask + private double size; // Volume resting on bid/ask level in base amount + + public level(double price, double size) { + this.price = price; + this.size = size; + } + + public double get_price() { + return price; + } + + public double get_size() { + return size; + } + } + + public static class orderbook { + private String symbol_id; // Our symbol identifier + private Timestamp time_exchange; // Exchange time of orderbook + private Timestamp time_coinapi; // CoinAPI time when orderbook received from exchange + private level[] bids; // Best 20 bid levels in order from best to worst + private level[] asks; // Best 20 ask levels in order from best to worst + + public orderbook(String symbol_id, Timestamp time_exchange, Timestamp time_coinapi, ArrayList bids, ArrayList asks) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.asks = new level[asks.size()]; + this.bids = new level[bids.size()]; + for (int i=0; i20) + nano = Integer.parseInt((time.substring(20,time.length()-1) + "0000000000").substring(0,7)) * 100; + + return new Timestamp(year, month, day, hours, minutes, seconds, nano); + } + + private static String precise_time_to_string(Timestamp timestamp) { + return String.format("%04d-%02d-%02dT%02d:%02d:%02d", timestamp.getYear() + 1900, timestamp.getMonth() + 1, timestamp.getDate(), timestamp.getHours(), timestamp.getMinutes(), timestamp.getSeconds()); + } + + private String get_json(String url) throws IOException, exception { + OkHttpClient client = new OkHttpClient(); + + RequestBody body = RequestBody.create(null, new byte[0]); + + Request request = new Request.Builder() + .url("https://rest.coinapi.io" + url) + //.post(body) + .addHeader("X-CoinAPI-Key", key) + .build(); + + //System.out.println(request.url().toString()); + + Response response = client.newCall(request).execute(); + + if (response.code()>=400) { + String error = "Error code " + response.code(); + + try { + JSONObject object = new JSONObject(response.body().string()); + error = object.getString("error"); + } + catch(Exception ex) { + } + + throw new exception(response.code(), error); + } + + return response.body().string(); + } + + public exchange[] list_all_exchanges() throws exception { + try { + String json = get_json("/v1/exchanges"); + JSONArray array = new JSONArray(json); + + exchange[] result = new exchange[array.length()]; + for (int i=0; i levels, JSONArray array) throws exception { + for (int i=0; i bids = new ArrayList(); + ArrayList asks = new ArrayList(); + if (object.has("asks")) { + parse_levels(asks, object.getJSONArray("asks")); + } + if (object.has("bids")) { + parse_levels(bids, object.getJSONArray("bids")); + } + return new orderbook(symbol_id, time_exchange, time_coinapi, bids, asks); + } + + private orderbook[] parse_orderbooks(JSONArray array) throws exception { + orderbook[] result = new orderbook[array.length()]; + for (int i=0; i Reformat Code to correct all sorts of style problems + + +2) the 2 other github issues are because of the wrong use of java.sql.Timestamp + --the best solution is to replace every usage of Timestamp with java.time.Instant + --as a consequence: + --these 2 methods of java_rest_coin_api_test were deleted: + precise_time_from_string + precise_time_to_string + + --discussion: + --could do this because coinapi intelligently chose to use timestamp strings in an ISO 8601 format that + 1) Java's Instant.parse method can directly parse with 100% accuracy + 2) Java's Instant.toString method directly returns + --this timestamp format always uses GMT with no daylight savings time, which is also known as "Zulu time" (hence the 'Z' for the time zone) + https://www.timeanddate.com/time/zone/timezone/zulu + https://www.timeanddate.com/worldclock/timezone/zulu + --eliminating the use of Timestamp also eliminated all but 1 of the compiler warnings + --the code in java_rest_coin_api_test.java where the user specifes times to download for is now human readable + + +3) java_rest_coin_api.get_json: + --eliminated the use of the custom exception inner class in favor of the Java builtin RuntimeException class + -both in the throws clause and the method body + --added code to first check if object has a value for "error" before call getString("error"); this eliminates an artificial JSONException from being thrown + --improved the message that this RuntimeException is created with to report all details + + +4) java_rest_coin_api.exception: + --deleted this inner class + --removed every " throws exception" in java_rest_coin_api + --removed every " throws java_rest_coin_api.exception" in java_rest_coin_api_test + --removed the "catch (java_rest_coin_api.exception ex)" in java_rest_coin_api_test.main + + +5) java_rest_coin_api: + --found all occurrences of this bad idiom: + try { + ... + } catch (IOException ioe) { + } + return null; + and ripped out the try/catch and added a throws clause to the method declaration if neccessary, typically + throws IOException + + +6) java_rest_coin_api_test: + --the removal of java_rest_coin_api's try/catch in favor of throwing Exceptions meant that many methods in this class needed to be updated to + a) no longer null check results + b) have their own + throws IOException + --removed main's try/catch in favor of + throws IOException + + +7) java_rest_coin_api.SYMBOL_TYPE: + --deleted the INVALID element + --should always throw an Exception instead of using a bogus value + --also, I do not see it listed among the symbol_type values here: https://docs.coinapi.io/#list-all-symbols + --deleted the symbol_type_from_string method and used the builtin Java enum valueOf method instead + + +8) java_rest_coin_api.OPTION_EXERCISE_STYLE: + --deleted the INVALID element + --should always throw an Exception instead of using a bogus value + --also, I do not see it listed among the option_exercise_style values here: https://docs.coinapi.io/#list-all-symbols + --consequences: + 1) in symbol(String symbol_id, String exchange_id, SYMBOL_TYPE symbol_type, String asset_id_base, String asset_id_quote) + had to change + this.option_exercise_style = OPTION_EXERCISE_STYLE.INVALID; + to + this.option_exercise_style = null; + 2) in list_all_symbols had to change the "new symbol..." passing of OPTION_EXERCISE_STYLE.INVALID to null + --deleted the option_exercise_style_from_string method and used the builtin Java enum valueOf method instead + + +9) java_rest_coin_api.PERIOD_IDENTIFIER: + --deleted the INVALID element + --should always throw an Exception instead of using a bogus value + --also, I do not see it listed among the Period identifiers values here: https://docs.coinapi.io/#list-all-periods + --added a coinapiValue method that turns the enum's identifier into the exact period_id that coinapi uses + --use that coinapiValue method in a new static parse method that replaces the old period_identifier_from_string method + --use that coinapiValue method in a new instance toString method that replaces the old period_id_to_string method + + +10) java_rest_coin_api.TRADE_SIDE: + --renamed TRADE_SIDE --> TAKER_SIDE + --deleted the INVALID element + --should always throw an Exception instead of using a bogus value + --also, I do not see it listed among the taker_side values here: https://docs.coinapi.io/#json-structure + --deleted the taker_size_from_string method and used the builtin Java enum valueOf method instead + + +11) java_rest_coin_api.key + --moved its declaration to the top of the file into a new dedicated instance fields section + --moved its accessor likewise + + +12) java_rest_coin_api_test: + --rearranged the methods into top down logical order, and added section labels + --scoured the file and made some small changes + + +13) java_rest_coin_api: + --moved all the inner classes/enums to top level classes/enums + + +14) renamed + java_rest_coin_api --> rest_methods + java_rest_coin_api_test --> rest_methods_test + + +15) in rest_methods (the former java_rest_coin_api): + --pulled the OkHttpClient client local var up into a field + --added a close method + --reason: top performance (see code comments) + + +16) in rest_methods_test (the former java_rest_coin_api_test): + --main now creates rest_methods instance and passes it as an arg to all the test methods + --those test methods now longer create their own rest_methods instance + + +17) renamed all the classes/enums to follow Java's naming convention + --mainly I just made the first letter be upper case + --I left in the underscores, since those are in the official coinapi names + diff --git a/data-api/java-rest/pom.xml b/data-api/java-rest/pom.xml new file mode 100644 index 0000000000..6278d7cf9a --- /dev/null +++ b/data-api/java-rest/pom.xml @@ -0,0 +1,156 @@ + + + + 4.0.0 + + io.coinapi.rest + v1 + 1.14 + + + COINAPI LTD + https://www.CoinAPI.io + + + + + github + coinapi.rest.v1 + https://maven.pkg.github.com/coinapi/coinapi-sdk + + + + + + MIT License + MIT License + + + + coinapi.rest.v1 + https://docs.coinapi.io + Java SDK for CoinAPI + + + tprzybysz + Tomasz Przybysz + tom.przybysz@gmail.com + + developer + + + + + + UTF-8 + 1.8 + 1.8 + + + + + junit + junit + 4.13.1 + test + + + com.squareup.okio + okio + 1.13.0 + + + com.squareup.okhttp3 + okhttp + 3.8.1 + + + org.json + json + 20140107 + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + default-deploy + deploy + + deploy + + + + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + attached + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + diff --git a/data-api/java-rest/publish.cmd b/data-api/java-rest/publish.cmd new file mode 100644 index 0000000000..c929ad5ecd --- /dev/null +++ b/data-api/java-rest/publish.cmd @@ -0,0 +1 @@ +mvn clean deploy -B release:prepare release:perform -DskipTests diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Asset.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Asset.java new file mode 100644 index 0000000000..10b6c6f019 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Asset.java @@ -0,0 +1,41 @@ +package io.coinapi.rest; + +/** + * Stores all the state for an asset, as described in https://docs.coinapi.io/#list-all-assets. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Asset { + + /** Our asset identifier. Superset of the ISO 4217 currency codes standard */ + private final String asset_id; // + + /** Display name of the asset */ + private final String name; + + /** true for cryptocurrency assets, false otherwise */ + private final boolean type_is_crypto; + + public Asset(String asset_id, String name, boolean type_is_crypto) { + this.asset_id = asset_id; + this.name = name; + this.type_is_crypto = type_is_crypto; + } + + public String get_asset_id() { + return asset_id; + } + + public String get_name() { + return name; + } + + public boolean is_type_crypto() { + return type_is_crypto; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Config.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Config.java new file mode 100644 index 0000000000..8df907ef6d --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Config.java @@ -0,0 +1,43 @@ +package io.coinapi.rest; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * File configuration support + */ +public class Config { + + private InputStream inputStream; + + /** + * Get value from config + * @param name + * @return + * @throws IOException + */ + public String getPropValues(String name) throws IOException { + + try { + Properties properties = new Properties(); + String fileName = "config.properties"; + + inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream != null) { + properties.load(inputStream); + } else { + throw new FileNotFoundException("property file " + fileName + " not found in the classpath"); + } + return properties.getProperty(name); + } + catch (Exception e) { + System.out.println(e); + } + finally { + inputStream.close(); + } + return null; + } +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange.java new file mode 100644 index 0000000000..46c2ca962f --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange.java @@ -0,0 +1,41 @@ +package io.coinapi.rest; + +/** + * Stores all the state for an exchange, as described in https://docs.coinapi.io/#list-all-exchanges. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Exchange { + + /** Our exchange identifier */ + private final String exchange_id; + + /** Display name of the exchange */ + private final String name; + + /** Exchange website address */ + private final String website; + + public Exchange(String exchange_id, String name, String website) { + this.exchange_id = exchange_id; + this.name = name; + this.website = website; + } + + public String get_exchange_id() { + return exchange_id; + } + + public String get_name() { + return name; + } + + public String get_website() { + return website; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange_rate.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange_rate.java new file mode 100644 index 0000000000..26e070d069 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Exchange_rate.java @@ -0,0 +1,51 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a current exchange rate, as described in https://docs.coinapi.io/#get-all-current-rates. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Exchange_rate { + + /** Time of the market data used to calculate exchange rate */ + private final Instant time; + + /** Exchange rate base asset identifier */ + private final String asset_id_base; + + /** Exchange rate quote asset identifier */ + private final String asset_id_quote; + + /** Exchange rate between assets */ + private final double rate; + + public Exchange_rate(Instant time, String asset_id_base, String asset_id_quote, double rate) { + this.time = time; + this.asset_id_base = asset_id_base; + this.asset_id_quote = asset_id_quote; + this.rate = rate; + } + + public Instant get_time() { + return time; + } + + public String get_asset_id_base() { + return asset_id_base; + } + + public String get_asset_id_quote() { + return asset_id_quote; + } + + public double get_rate() { + return rate; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Level.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Level.java new file mode 100644 index 0000000000..ba08931086 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Level.java @@ -0,0 +1,33 @@ +package io.coinapi.rest; + +/** + * Stores all the state for an orderbook level, as described in https://docs.coinapi.io/#order-book. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Level { + + /** Price of bid/ask */ + private final double price; + + /** Volume resting on bid/ask level in base amount */ + private final double size; + + public Level(double price, double size) { + this.price = price; + this.size = size; + } + + public double get_price() { + return price; + } + + public double get_size() { + return size; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/OptionExerciseStyle.java b/data-api/java-rest/src/main/java/io/coinapi/rest/OptionExerciseStyle.java new file mode 100644 index 0000000000..c094952623 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/OptionExerciseStyle.java @@ -0,0 +1,10 @@ +package io.coinapi.rest; + +/** + * Option exercise style. Can be EUROPEAN or AMERICAN + */ +public class OptionExerciseStyle { + + public static final String EUROPEAN = "EUROPEAN"; + public static final String AMERICAN = "AMERICAN"; +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Orderbook.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Orderbook.java new file mode 100644 index 0000000000..21b485aeec --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Orderbook.java @@ -0,0 +1,74 @@ +package io.coinapi.rest; + +import java.time.Instant; +import java.util.ArrayList; + +/** + * Stores all the state for an orderbook, as described in https://docs.coinapi.io/#order-book. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Orderbook { + + /** Our symbol identifier */ + private final String symbol_id; + + /** Exchange time of orderbook */ + private final Instant time_exchange; + + /** CoinAPI time when orderbook received from exchange */ + private final Instant time_coinapi; + + /** Best 20 bid levels in order from best to worst */ + private final Level[] bids; + + /** Best 20 ask levels in order from best to worst */ + private final Level[] asks; + + public Orderbook(String symbol_id, Instant time_exchange, Instant time_coinapi, ArrayList bids, ArrayList asks) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.asks = new Level[asks.size()]; + this.bids = new Level[bids.size()]; + for (int i = 0; i < asks.size(); i++) { + this.asks[i] = asks.get(i); + } + for (int i = 0; i < bids.size(); i++) { + this.bids[i] = bids.get(i); + } + } + + public String get_symbol_id() { + return symbol_id; + } + + public Instant get_time_exchange() { + return time_exchange; + } + + public Instant get_time_coinapi() { + return time_coinapi; + } + + public int get_bids_count() { + return bids.length; + } + + public int get_asks_count() { + return asks.length; + } + + public Level get_bid(int index) { + return bids[index]; + } + + public Level get_ask(int index) { + return asks[index]; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Period.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Period.java new file mode 100644 index 0000000000..ad94146e47 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Period.java @@ -0,0 +1,65 @@ +package io.coinapi.rest; + +/** + * Stores all the state for a period, as described in https://docs.coinapi.io/#list-all-periods. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Period { + + /** Period identifier, used in other API calls */ + private final Period_identifier period_id; + + /** Seconds part of period length */ + private final int length_seconds; + + /** Months part of period length */ + private final int length_months; + + /** Period length in units */ + private final int unit_count; + + /** Type of unit (second/minute/hour/day/month/year) */ + private final String unit_name; + + /** Display name of period length */ + private final String display_name; + + public Period(Period_identifier period_id, int length_seconds, int length_months, int unit_count, String unit_name, String display_name) { + this.period_id = period_id; + this.length_seconds = length_seconds; + this.length_months = length_months; + this.unit_count = unit_count; + this.unit_name = unit_name; + this.display_name = display_name; + } + + public Period_identifier get_period_id() { + return period_id; + } + + public int get_length_seconds() { + return length_seconds; + } + + public int get_length_months() { + return length_months; + } + + public int get_unit_count() { + return unit_count; + } + + public String get_unit_name() { + return unit_name; + } + + public String get_display_name() { + return display_name; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Period_identifier.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Period_identifier.java new file mode 100644 index 0000000000..543dc3fcfb --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Period_identifier.java @@ -0,0 +1,97 @@ +package io.coinapi.rest; + +/** + * Defines all the elements of a Period identifier, as described in https://docs.coinapi.io/#list-all-periods. + *

+ * This enum is multithread safe: it is stateless (except for the enumeration of values, which are immutable). + *

+ * Like all java enums, this enum is Comparable and Serializable. + *

+ * @see Enum documentation + */ +public enum Period_identifier { + + _1SEC, + _2SEC, + _3SEC, + _4SEC, + _5SEC, + _6SEC, + _10SEC, + _15SEC, + _20SEC, + _30SEC, + _1MIN, + _2MIN, + _3MIN, + _4MIN, + _5MIN, + _6MIN, + _10MIN, + _15MIN, + _20MIN, + _30MIN, + _1HRS, + _2HRS, + _3HRS, + _4HRS, + _6HRS, + _8HRS, + _12HRS, + _1DAY, + _2DAY, + _3DAY, + _5DAY, + _7DAY, + _10DAY, + _1MTH, + _2MTH, + _3MTH, + _4MTH, + _6MTH, + _1YRS, + _2YRS, + _3YRS, + _4YRS, + _5YRS; + + // defensive code: check that every enum identifier above starts with an underscore: + // --failure to do so means that the coinapiValue method below is broken + static { + for (Period_identifier period_identifier : values()) { + if (!period_identifier.name().startsWith("_")) + throw new IllegalStateException("enum element " + period_identifier.name() + " fails to start with an underscore ('_')"); + } + } + + /** + * Similar to the builtin Java enum method {@link #valueOf(String) valueOf}, + * except that arg s must be the actual period ID value that coinapi uses. + * In other words, s must start with a digit, not an underscore ('_') char. + *

+ * @throws IllegalArgumentException if s does not equal a supported period ID value + */ + public static Period_identifier parse(String s) throws IllegalArgumentException { + for (Period_identifier pi : values()) { + if (pi.coinapiValue().equals(s)) return pi; + } + throw new IllegalArgumentException("s = " + s + " is an unsupported value"); + } + + @Override public String toString() { + return coinapiValue(); + } + + /** + * Returns the actual period ID value that coinapi uses for this element. + *

+ * The names of the enum elements above, unfortunately, cannot exactly equal their coinapi values because Java identifiers may not start with a digit. + * That is why all the enum elements above start with an underscore ('_'). + * So, this method returns the element identifier's characters after the first char; in effect, it drops the initial underscore char. + */ + private String coinapiValue() { + return name().substring(1); + } + // If top performance is needed, this method should be replaced with a private final String field that caches the result that this method calculates each time. + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Quote.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Quote.java new file mode 100644 index 0000000000..813baa4a13 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Quote.java @@ -0,0 +1,79 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a latest quote, as described in https://docs.coinapi.io/#latest-data33. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Quote { + + /** Our symbol identifier */ + private final String symbol_id; + + /** Exchange time of orderbook */ + private final Instant time_exchange; + + /** CoinAPI time when orderbook received from exchange */ + private final Instant time_coinapi; + + /** Best asking price */ + private final double ask_price; + + /** Volume resting on best ask */ + private final double ask_size; + + /** Best bidding price */ + private final double bid_price; + + /** Volume resting on best bid */ + private final double bid_size; + + public Quote(String symbol_id, Instant time_exchange, Instant time_coinapi, double ask_price, double ask_size, double bid_price, double bid_size) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.ask_price = ask_price; + this.ask_size = ask_size; + this.bid_price = bid_price; + this.bid_size = bid_size; + } + + public String get_symbol_id() { + return symbol_id; + } + + public Instant get_time_exchange() { + return time_exchange; + } + + public Instant get_time_coinapi() { + return time_coinapi; + } + + public double get_ask_price() { + return ask_price; + } + + public double get_ask_size() { + return ask_size; + } + + public double get_bid_price() { + return bid_price; + } + + public double get_bid_size() { + return bid_size; + } + + public boolean has_last_trade() { + return false; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Quote_with_trade.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Quote_with_trade.java new file mode 100644 index 0000000000..dc85358dc6 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Quote_with_trade.java @@ -0,0 +1,35 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a quote with a trade, as described in https://docs.coinapi.io/#current-data32. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Quote_with_trade extends Quote { + + /** Last executed transaction */ + private final Trade last_trade; + + public Quote_with_trade( + String symbol_id, Instant time_exchange, Instant time_coinapi, + double ask_price, double ask_size, double bid_price, double bid_size, Trade last_trade + ) { + super(symbol_id, time_exchange, time_coinapi, ask_price, ask_size, bid_price, bid_size); + this.last_trade = last_trade; + } + + @Override public boolean has_last_trade() { + return last_trade != null; + } + + public Trade get_last_trade() { + return last_trade; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/REST_methods.java b/data-api/java-rest/src/main/java/io/coinapi/rest/REST_methods.java new file mode 100644 index 0000000000..2c0d25d247 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/REST_methods.java @@ -0,0 +1,626 @@ +package io.coinapi.rest; + +import java.io.Closeable; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * Contains methods that call coinapi's REST API. + *

+ * This class is multithread safe. + * It is always properly constructed. + * All of its fields are final. + * Its {@link #key} field is immutable, while its {@link #client} field is a multithread safe type. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class REST_methods implements Closeable { + + // -------------------- instance fields -------------------- + + private final String key; + + // For top performance, it is critical that you cache the OkHttpClient instance: + // OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. + // This is because each client holds its own connection pool and thread pools. + // Reusing connections and threads reduces latency and saves memory. + // Conversely, creating a client for each request wastes resources on idle pools. + // https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html + private final OkHttpClient client = new OkHttpClient(); + + // -------------------- constructor -------------------- + + public REST_methods(String key) { + this.key = key; + } + + // -------------------- close -------------------- + + @Override public void close() { + // The code below is described in the "Shutdown isn't necessary" section here: https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html + client.dispatcher().executorService().shutdown(); + client.connectionPool().evictAll(); + //client.cache().close(); // only call this if client was created with a cache; the one above was NOT + } + + // -------------------- get_json -------------------- + + private String get_json(String url) throws IOException { + //RequestBody body = RequestBody.create(null, new byte[0]); + + Request request = new Request.Builder() + .url("https://rest.coinapi.io" + url) + //.post(body) + .addHeader("X-CoinAPI-Key", key) + .build(); + + try ( + Response response = client.newCall(request).execute() // you MUST always immediately close response, easiest way is like this; see https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html + ) { + ResponseBody body = response.body(); // no need to null check the result of body(): it is annotated @Nullable but its javadoc states that "Returns a non-null value if this response was ... returned from Call.execute()" which is the case above; see https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#body-- + + if (response.code() >= 400) { + String error; + try { + JSONObject object = new JSONObject(body.string()); + if (object.has("error")) { + error = object.getString("error"); + } else { + error = "[NOTHING: response has no value for \"error\"]"; + } + } catch (Throwable t) { + error = "[FAILED to extract response's \"error\" value because this Throwable was raised: " + t + "]"; + } + + String message = + "the response code for url is an ERROR code:" + "\n" + + "\t" + "url = " + url + "\n" + + "\t" + "response code = " + response.code() + "\n" + + "\t" + "response body error = " + error + "\n"; + + throw new RuntimeException(message); + } + + return body.string(); + } + } + + // -------------------- public API methods (and private helper methods) -------------------- + + public Exchange[] list_all_exchanges() throws IOException { + String json = get_json("/v1/exchanges"); + JSONArray array = new JSONArray(json); + + Exchange[] result = new Exchange[array.length()]; + for (int i = 0; i < array.length(); i++) { + String exchange_id = array.getJSONObject(i).getString("exchange_id"); + String name = array.getJSONObject(i).getString("name"); + String website = array.getJSONObject(i).getString("website"); + result[i] = new Exchange(exchange_id, name, website); + } + return result; + } + + public Asset[] list_all_assets() throws IOException { + String json = get_json("/v1/assets"); + JSONArray array = new JSONArray(json); + + Asset[] result = new Asset[array.length()]; + for (int i = 0; i < array.length(); i++) { + String asset_id = array.getJSONObject(i).getString("asset_id"); + String name = array.getJSONObject(i).optString("name", null); + boolean type_is_crypto = array.getJSONObject(i).getInt("type_is_crypto") != 0; + result[i] = new Asset(asset_id, name, type_is_crypto); + } + return result; + } + + public Symbol[] list_all_symbols() throws IOException { + String json = get_json("/v1/symbols"); + JSONArray array = new JSONArray(json); + + Symbol[] result = new Symbol[array.length()]; + for (int i = 0; i < array.length(); i++) { + String symbol_id = array.getJSONObject(i).getString("symbol_id"); + String exchange_id = array.getJSONObject(i).getString("exchange_id"); + String symbol_type = array.getJSONObject(i).getString("symbol_type"); + String asset_id_base = UtilsJSON.parseStringFromJson("asset_id_base", array.getJSONObject(i)); + String asset_id_quote = UtilsJSON.parseStringFromJson("asset_id_quote", array.getJSONObject(i)); + String asset_id_unit = UtilsJSON.parseStringFromJson("asset_id_unit", array.getJSONObject(i)); + String data_start = UtilsJSON.parseStringFromJson("data_start", array.getJSONObject(i)); + String data_end = UtilsJSON.parseStringFromJson("data_end", array.getJSONObject(i)); + Double volume_1hrs = UtilsJSON.parseDoubleFromJson("volume_1hrs", array.getJSONObject(i)); + Double volume_1hrs_usd = UtilsJSON.parseDoubleFromJson("volume_1hrs_usd", array.getJSONObject(i)); + Double volume_1day = UtilsJSON.parseDoubleFromJson("volume_1day", array.getJSONObject(i)); + Double volume_1day_usd = UtilsJSON.parseDoubleFromJson("volume_1day_usd", array.getJSONObject(i)); + Double volume_1mth = UtilsJSON.parseDoubleFromJson("volume_1mth", array.getJSONObject(i)); + Double volume_1mth_usd = UtilsJSON.parseDoubleFromJson("volume_1mth_usd", array.getJSONObject(i)); + String index_id = UtilsJSON.parseStringFromJson("index_id", array.getJSONObject(i)); + String index_display_name = UtilsJSON.parseStringFromJson("index_display_name", array.getJSONObject(i)); + String index_display_description = UtilsJSON.parseStringFromJson("index_display_description", array.getJSONObject(i)); + Instant future_delivery_time = UtilsJSON.parseInstantFromJson("future_delivery_time", array.getJSONObject(i)); + Integer future_contract_unit = UtilsJSON.parseIntegerFromJson("future_contract_unit", array.getJSONObject(i)); + String future_contract_unit_asset = UtilsJSON.parseStringFromJson("future_contract_unit_asset", array.getJSONObject(i)); + Boolean option_type_is_call = UtilsJSON.parseBooleanFromJson("option_type_is_call", array.getJSONObject(i)); + Double option_strike_price = UtilsJSON.parseDoubleFromJson("option_strike_price", array.getJSONObject(i)); + Double option_contract_unit = UtilsJSON.parseDoubleFromJson("option_contract_unit", array.getJSONObject(i)); + String option_exercise_style = UtilsJSON.parseStringFromJson("option_exercise_style", array.getJSONObject(i)); + Instant option_expiration_time = UtilsJSON.parseInstantFromJson("option_expiration_time", array.getJSONObject(i)); + + result[i] = new Symbol(symbol_id, exchange_id, symbol_type, asset_id_base, asset_id_quote, asset_id_unit, data_start, data_end, + volume_1hrs, volume_1hrs_usd, volume_1day, volume_1day_usd, volume_1mth, volume_1mth_usd, index_id, index_display_name, index_display_description, + future_delivery_time, future_contract_unit, future_contract_unit_asset, option_type_is_call, option_strike_price, option_contract_unit, + option_exercise_style, option_expiration_time); + } + return result; + } + + public Exchange_rate get_exchange_rate(String asset_id_base, String asset_id_quote) throws IOException { + String json = get_json("/v1/exchangerate/" + asset_id_base + "/" + asset_id_quote); + JSONObject object = new JSONObject(json); + + asset_id_base = object.getString("asset_id_base"); + asset_id_quote = object.getString("asset_id_quote"); + double rate = object.getDouble("rate"); + + return new Exchange_rate(Instant.parse(object.getString("time")), asset_id_base, asset_id_quote, rate); + } + + public Exchange_rate get_exchange_rate(String asset_id_base, String asset_id_quote, Instant time) throws IOException { + String json = get_json("/v1/exchangerate/" + asset_id_base + "/" + asset_id_quote + "?time=" + time); + JSONObject object = new JSONObject(json); + + asset_id_base = object.getString("asset_id_base"); + asset_id_quote = object.getString("asset_id_quote"); + double rate = object.getDouble("rate"); + return new Exchange_rate(Instant.parse(object.getString("time")), asset_id_base, asset_id_quote, rate); + } + + public Exchange_rate[] get_all_exchange_rates(String asset_id_base) throws IOException { + String json = get_json("/v1/exchangerate/" + asset_id_base); + JSONObject object = new JSONObject(json); + JSONArray array = object.getJSONArray("rates"); + + Exchange_rate[] result = new Exchange_rate[array.length()]; + for (int i = 0; i < array.length(); i++) { + String asset_id_quote = array.getJSONObject(i).getString("asset_id_quote"); + double rate = array.getJSONObject(i).getDouble("rate"); + Instant time = Instant.parse(array.getJSONObject(i).getString("time")); + result[i] = new Exchange_rate(time, asset_id_base, asset_id_quote, rate); + } + return result; + } + + public Period[] ohlcv_list_all_periods() throws IOException { + String json = get_json("/v1/ohlcv/periods"); + JSONArray array = new JSONArray(json); + + Period[] result = new Period[array.length()]; + for (int i = 0; i < array.length(); i++) { + Period_identifier period_id = Period_identifier.parse(array.getJSONObject(i).getString("period_id")); + int length_seconds = array.getJSONObject(i).getInt("length_seconds"); + int length_months = array.getJSONObject(i).getInt("length_months"); + int unit_count = array.getJSONObject(i).getInt("unit_count"); + String unit_name = array.getJSONObject(i).getString("unit_name"); + String display_name = array.getJSONObject(i).getString("display_name"); + + result[i] = new Period(period_id, length_seconds, length_months, unit_count, unit_name, display_name); + } + return result; + } + + private Timedata[] parse_timeseries(JSONArray array) { + Timedata[] result = new Timedata[array.length()]; + for (int i = 0; i < array.length(); i++) { + Instant time_period_start = Instant.parse(array.getJSONObject(i).getString("time_period_start")); + Instant time_period_end = Instant.parse(array.getJSONObject(i).getString("time_period_end")); + Instant time_open = Instant.parse(array.getJSONObject(i).getString("time_open")); + Instant time_close = Instant.parse(array.getJSONObject(i).getString("time_close")); + double price_open = array.getJSONObject(i).getDouble("price_open"); + double price_high = array.getJSONObject(i).getDouble("price_high"); + double price_low = array.getJSONObject(i).getDouble("price_low"); + double price_close = array.getJSONObject(i).getDouble("price_close"); + double volume_traded = array.getJSONObject(i).getDouble("volume_traded"); + int trades_count = array.getJSONObject(i).getInt("trades_count"); + + result[i] = new Timedata(time_period_start, time_period_end, time_open, time_close, price_open, price_high, price_low, price_close, volume_traded, trades_count); + } + return result; + } + + public Timedata[] ohlcv_get_latest_timeseries(String symbol_id, Period_identifier period_id) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/latest?period_id=" + period_id); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_latest_timeseries(String symbol_id, Period_identifier period_id, int limit) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/latest?period_id=" + period_id + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, Instant time_start) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, String time_start) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, Instant time_start, Instant time_end) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, String time_start, String time_end) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, Instant time_start, int limit) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, String time_start, int limit) throws IOException { + String json = get_json("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + public Timedata[] ohlcv_get_historical_timeseries(String symbol_id, Period_identifier period_id, Instant time_start, Instant time_end, int limit) throws IOException { + String json = get_json( + "/v1/ohlcv/" + symbol_id + + "/history?" + + "period_id=" + period_id + + "&time_start=" + time_start + + "&time_end=" + time_end + + "&limit=" + limit + ); + JSONArray array = new JSONArray(json); + return parse_timeseries(array); + } + + private Trade parse_trade(JSONObject object, String symbol_id) { + if (symbol_id == null) symbol_id = object.getString("symbol_id"); + Instant time_exchange = Instant.parse(object.getString("time_exchange")); + Instant time_coinapi = Instant.parse(object.getString("time_coinapi")); + String uuid = object.getString("uuid"); + double price = object.getDouble("price"); + double size = object.getDouble("size"); + Taker_side taker_side = Taker_side.valueOf(object.getString("taker_side")); + + return new Trade(symbol_id, time_exchange, time_coinapi, uuid, price, size, taker_side); + } + + private Trade[] parse_trades(JSONArray array) { + Trade[] result = new Trade[array.length()]; + + for (int i = 0; i < array.length(); i++) { + result[i] = parse_trade(array.getJSONObject(i), null); + } + return result; + } + + private Quote_with_trade parse_quote_with_trade(JSONObject object) { + String symbol_id = object.getString("symbol_id"); + Instant time_exchange = Instant.parse(object.getString("time_exchange")); + Instant time_coinapi = Instant.parse(object.getString("time_coinapi")); + double ask_price = object.getDouble("ask_price"); + double ask_size = object.getDouble("ask_size"); + double bid_price = object.getDouble("bid_price"); + double bid_size = object.getDouble("bid_size"); + Trade last_trade = null; + if (object.has("last_trade")) last_trade = parse_trade(object.getJSONObject("last_trade"), symbol_id); + return new Quote_with_trade(symbol_id, time_exchange, time_coinapi, ask_price, ask_size, bid_price, bid_size, last_trade); + } + + private Quote parse_quote(JSONObject object) { + String symbol_id = object.getString("symbol_id"); + Instant time_exchange = Instant.parse(object.getString("time_exchange")); + Instant time_coinapi = Instant.parse(object.getString("time_coinapi")); + double ask_price = object.getDouble("ask_price"); + double ask_size = object.getDouble("ask_size"); + double bid_price = object.getDouble("bid_price"); + double bid_size = object.getDouble("bid_size"); + return new Quote(symbol_id, time_exchange, time_coinapi, ask_price, ask_size, bid_price, bid_size); + } + + private Quote_with_trade[] parse_quotes_with_trade(JSONArray array) { + Quote_with_trade[] result = new Quote_with_trade[array.length()]; + for (int i = 0; i < array.length(); i++) { + result[i] = parse_quote_with_trade(array.getJSONObject(i)); + } + return result; + } + + private Quote[] parse_quotes(JSONArray array) { + Quote[] result = new Quote[array.length()]; + for (int i = 0; i < array.length(); i++) { + result[i] = parse_quote(array.getJSONObject(i)); + } + return result; + } + + private void parse_levels(ArrayList levels, JSONArray array) { + for (int i = 0; i < array.length(); i++) { + double price = array.getJSONObject(i).getDouble("price"); + double size = array.getJSONObject(i).getDouble("size"); + levels.add(new Level(price, size)); + } + } + + private Orderbook parse_orderbook(JSONObject object) { + String symbol_id = object.getString("symbol_id"); + Instant time_exchange = Instant.parse(object.getString("time_exchange")); + Instant time_coinapi = Instant.parse(object.getString("time_coinapi")); + ArrayList bids = new ArrayList(); + ArrayList asks = new ArrayList(); + if (object.has("asks")) { + parse_levels(asks, object.getJSONArray("asks")); + } + if (object.has("bids")) { + parse_levels(bids, object.getJSONArray("bids")); + } + return new Orderbook(symbol_id, time_exchange, time_coinapi, bids, asks); + } + + private Orderbook[] parse_orderbooks(JSONArray array) { + Orderbook[] result = new Orderbook[array.length()]; + for (int i = 0; i < array.length(); i++) { + result[i] = parse_orderbook(array.getJSONObject(i)); + } + return result; + } + + public Trade[] trades_get_latest_data() throws IOException { + String json = get_json("/v1/trades/latest"); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_latest_data(int limit) throws IOException { + String json = get_json("/v1/trades/latest?limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_latest_data(String symbol_id) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/latest"); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_latest_data(String symbol_id, int limit) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/latest?limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, Instant time_start) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, String time_start) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, Instant time_start, int limit) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, String time_start, int limit) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, Instant time_start, Instant time_end) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, String time_start, String time_end) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, Instant time_start, Instant time_end, int limit) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Trade[] trades_get_historical_data(String symbol_id, String time_start, String time_end, int limit) throws IOException { + String json = get_json("/v1/trades/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_trades(array); + } + + public Quote_with_trade[] quotes_get_for_all_symbols() throws IOException { + String json = get_json("/v1/quotes/current"); + JSONArray array = new JSONArray(json); + return parse_quotes_with_trade(array); + } + + public Quote_with_trade quotes_get_for_symbol(String symbol_id) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/current"); + JSONObject object = new JSONObject(json); + return parse_quote_with_trade(object); + } + + public Quote[] quotes_get_latest_data() throws IOException { + String json = get_json("/v1/quotes/latest"); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_latest_data(int limit) throws IOException { + String json = get_json("/v1/quotes/latest?limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_latest_data(String symbol_id) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/latest"); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_latest_data(String symbol_id, int limit) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/latest?limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, Instant time_start) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, String time_start) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, Instant time_start, int limit) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, String time_start, int limit) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, Instant time_start, Instant time_end) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + public Quote[] quotes_get_historical_data(String symbol_id, String time_start, String time_end) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, Instant time_start, Instant time_end, int limit) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Quote[] quotes_get_historical_data(String symbol_id, String time_start, String time_end, int limit) throws IOException { + String json = get_json("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_quotes(array); + } + + public Orderbook[] orderbooks_get_for_all_symbols() throws IOException { + String json = get_json("/v1/orderbooks/current"); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook orderbooks_get_for_symbol(String symbol_id) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/current"); + JSONObject object = new JSONObject(json); + return parse_orderbook(object); + } + + public Orderbook[] orderbooks_get_latest_data(String symbol_id) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/latest"); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_latest_data(String symbol_id, int limit) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/latest?limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, Instant time_start) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, String time_start) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, Instant time_start, int limit) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, String time_start, int limit) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, Instant time_start, Instant time_end) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, String time_start, String time_end) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, Instant time_start, Instant time_end, int limit) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + public Orderbook[] orderbooks_get_historical_data(String symbol_id, String time_start, String time_end, int limit) throws IOException { + String json = get_json("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start + "&time_end=" + time_end + "&limit=" + limit); + JSONArray array = new JSONArray(json); + return parse_orderbooks(array); + } + + private int[] parse_int_array(JSONArray array) { + int[] result = new int[array.length()]; + for (int i = 0; i < array.length(); i++) { + result[i] = array.getInt(i); + } + return result; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Symbol.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Symbol.java new file mode 100644 index 0000000000..80af1db7ec --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Symbol.java @@ -0,0 +1,218 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a symbol, as described in https://docs.coinapi.io/#list-all-symbols. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Symbol { + + /** Our symbol identifier, see table below for format description. */ + private final String symbol_id; + + /** Our identifier of the exchange where symbol is traded. */ + private final String exchange_id; + + /** Type of symbol (possible values are: SPOT, FUTURES or OPTION) */ + private final String symbol_type; + + /** FX Spot base asset identifier, for derivatives it's contact underlying (e.g. BTC for BTC/USD) */ + private final String asset_id_base; + + /** FX Spot quote asset identifier, for derivatives it's contract underlying (e.g. USD for BTC/USD) */ + private final String asset_id_quote; + + /** Identifier of the symbol unit asset used to denominate: transactions and order books volume (optional, if not provided then data is denominated in asset_id_base) */ + private final String asset_id_unit; + + /** Date of the first data point */ + private final String data_start; + + /** Date of the last data point */ + private final String data_end; + + /** Last 1 hour volume denominated in symbol unit asset */ + private final Double volume_1hrs; + + /** Last 1 hour volume in USD */ + private final Double volume_1hrs_usd; + + /** Last 1 day volume denominated in symbol unit asset */ + private final Double volume_1day; + + /** Last 1 day volume in USD */ + private final Double volume_1day_usd; + + /** Last 1 month volume denominated in symbol unit asset */ + private final Double volume_1mth; + + /** Last 1 month volume in USD */ + private final Double volume_1mth_usd; + + /** Index identifier */ + private final String index_id; + + /** Human readable name of the index (optional) */ + private final String index_display_name; + + /** Description of the index (optional) */ + private final String index_display_description; + + /** Predetermined time of futures contract delivery date in ISO 8601 */ + private final Instant future_delivery_time; + + /** Contact size (eg. 10 BTC if future_contract_unit = 10 and future_contract_unit_asset = BTC) */ + private final Integer future_contract_unit; + + /** Identifier of the asset used to denominate the contract unit */ + private final String future_contract_unit_asset; + + /** Boolean value representing option type. true for Call options, false for Put options */ + private final Boolean option_type_is_call; + + /** Price at which option contract can be exercised */ + private final Double option_strike_price; + + /** Base asset amount of underlying spot which single option represents */ + private final Double option_contract_unit; + + /** Option exercise style. Can be EUROPEAN or AMERICAN */ + private final String option_exercise_style; + + /** Option contract expiration time */ + private final Instant option_expiration_time; + + public Symbol(String symbol_id, String exchange_id, String symbol_type, String asset_id_base, String asset_id_quote, String asset_id_unit, String data_start, String data_end, Double volume_1hrs, Double volume_1hrs_usd, Double volume_1day, Double volume_1day_usd, Double volume_1mth, Double volume_1mth_usd, String index_id, String index_display_name, String index_display_description, Instant future_delivery_time, Integer future_contract_unit, String future_contract_unit_asset, Boolean option_type_is_call, Double option_strike_price, Double option_contract_unit, String option_exercise_style, Instant option_expiration_time) { + this.symbol_id = symbol_id; + this.exchange_id = exchange_id; + this.symbol_type = symbol_type; + this.asset_id_base = asset_id_base; + this.asset_id_quote = asset_id_quote; + this.asset_id_unit = asset_id_unit; + this.data_start = data_start; + this.data_end = data_end; + this.volume_1hrs = volume_1hrs; + this.volume_1hrs_usd = volume_1hrs_usd; + this.volume_1day = volume_1day; + this.volume_1day_usd = volume_1day_usd; + this.volume_1mth = volume_1mth; + this.volume_1mth_usd = volume_1mth_usd; + this.index_id = index_id; + this.index_display_name = index_display_name; + this.index_display_description = index_display_description; + this.future_delivery_time = future_delivery_time; + this.future_contract_unit = future_contract_unit; + this.future_contract_unit_asset = future_contract_unit_asset; + this.option_type_is_call = option_type_is_call; + this.option_strike_price = option_strike_price; + this.option_contract_unit = option_contract_unit; + this.option_exercise_style = option_exercise_style; + this.option_expiration_time = option_expiration_time; + } + + public String get_symbol_id() { + return symbol_id; + } + + public String get_exchange_id() { + return exchange_id; + } + + public String get_symbol_type() { + return symbol_type; + } + + public String get_asset_id_base() { + return asset_id_base; + } + + public String get_asset_id_quote() { + return asset_id_quote; + } + + public String get_asset_id_unit() { + return asset_id_unit; + } + + public String get_data_start() { + return data_start; + } + + public String get_data_end() { + return data_end; + } + + public Double get_volume_1hrs() { + return volume_1hrs; + } + + public Double get_volume_1hrs_usd() { + return volume_1hrs_usd; + } + + public Double get_volume_1day() { + return volume_1day; + } + + public Double get_volume_1day_usd() { + return volume_1day_usd; + } + + public Double get_volume_1mth() { + return volume_1mth; + } + + public Double get_volume_1mth_usd() { + return volume_1mth_usd; + } + + public String get_index_id() { + return index_id; + } + + public String get_index_display_name() { + return index_display_name; + } + + public String get_index_display_description() { + return index_display_description; + } + + public Instant get_future_delivery_time() { + return future_delivery_time; + } + + public Integer get_future_contract_unit() { + return future_contract_unit; + } + + public String get_future_contract_unit_asset() { + return future_contract_unit_asset; + } + + public Boolean get_is_option_type_is_call() { + return option_type_is_call; + } + + public Double get_option_strike_price() { + return option_strike_price; + } + + public Double get_option_contract_unit() { + return option_contract_unit; + } + + public String get_option_exercise_style() { + return option_exercise_style; + } + + public Instant get_option_expiration_time() { + return option_expiration_time; + } +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/SymbolType.java b/data-api/java-rest/src/main/java/io/coinapi/rest/SymbolType.java new file mode 100644 index 0000000000..48b903b9d9 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/SymbolType.java @@ -0,0 +1,32 @@ +package io.coinapi.rest; + +/** + * Symbol types list (enumeration of symbol_type output variable) + */ +public class SymbolType { + + /** + * FX Spot. Agreement to exchange one asset for another one (e.g. Buy BTC for USD) + */ + public static final String SPOT = "SPOT"; + + /** + * Futures contract. FX Spot derivative contract where traders agree to trade fx spot at predetermined future time + */ + public static final String FUTURES = "FUTURES"; + + /** + * Option contract. FX Spot derivative contract where traders agree to trade right to require buy or sell of fx spot at agreed price on exercise date + */ + public static final String OPTION = "OPTION"; + + /** + * Perpetual contract. FX Spot derivative contract where traders agree to trade fx spot continously without predetermined future delivery time + */ + public static final String PERPETUAL = "PERPETUAL"; + + /** + * Index. Statistical composite that measures changes in the economy or markets. + */ + public static final String INDEX = "INDEX"; +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Taker_side.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Taker_side.java new file mode 100644 index 0000000000..cb55eedd5c --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Taker_side.java @@ -0,0 +1,20 @@ +package io.coinapi.rest; + +/** + * Defines all the elements of a taker_side, as described in https://docs.coinapi.io/#json-structure. + *

+ * This enum is multithread safe: it is stateless (except for the enumeration of values, which are immutable). + *

+ * Like all java enums, this enum is Comparable and Serializable. + *

+ * @see Enum documentation + */ +public enum Taker_side { + + BUY, + SELL, + BUY_ESTIMATED, + SELL_ESTIMATED, + UNKNOWN; + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Timedata.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Timedata.java new file mode 100644 index 0000000000..dfac74d539 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Timedata.java @@ -0,0 +1,102 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a timeseries data, as described in https://docs.coinapi.io/#latest-data. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Timedata { + + /** Period starting time (range left inclusive) */ + private final Instant time_period_start; + + /** Period ending time (range right exclusive) */ + private final Instant time_period_end; + + /** Time of first trade inside period range */ + private final Instant time_open; + + /** Time of last trade inside period range */ + private final Instant time_close; + + /** First trade price inside period range */ + private final double price_open; + + /** Highest traded price inside period range */ + private final double price_high; + + /** Lowest traded price inside period range */ + private final double price_low; + + /** Last trade price inside period range */ + private final double price_close; + + /** Cumulative base amount traded inside period range */ + private final double volume_traded; + + /** Amount of trades executed inside period range */ + private final int trades_count; + + public Timedata( + Instant time_period_start, Instant time_period_end, Instant time_open, Instant time_close, + double price_open, double price_high, double price_low, double price_close, double volume_traded, int trades_count + ) { + this.time_period_start = time_period_start; + this.time_period_end = time_period_end; + this.time_open = time_open; + this.time_close = time_close; + this.price_open = price_open; + this.price_high = price_high; + this.price_low = price_low; + this.price_close = price_close; + this.volume_traded = volume_traded; + this.trades_count = trades_count; + } + + public Instant get_time_period_start() { + return time_period_start; + } + + public Instant get_time_period_end() { + return time_period_end; + } + + public Instant get_time_open() { + return time_open; + } + + public Instant get_time_close() { + return time_close; + } + + public double get_price_open() { + return price_open; + } + + public double get_price_high() { + return price_high; + } + + public double get_price_low() { + return price_low; + } + + public double get_price_close() { + return price_close; + } + + public double get_volume_traded() { + return volume_traded; + } + + public int get_trades_count() { + return trades_count; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/Trade.java b/data-api/java-rest/src/main/java/io/coinapi/rest/Trade.java new file mode 100644 index 0000000000..2bbdf392d6 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/Trade.java @@ -0,0 +1,75 @@ +package io.coinapi.rest; + +import java.time.Instant; + +/** + * Stores all the state for a trade, as described in https://docs.coinapi.io/#json-structure. + *

+ * This class is multithread safe: it is immutable. + * In particular, it is always properly constructed, + * all of its fields are final, + * and none of their state can be changed after construction. + * See p. 53 of Java Concurrency In Practice for more discussion. + */ +public class Trade { + + /** Our symbol identifier */ + private final String symbol_id; + + /** Time of trade reported by exchange */ + private final Instant time_exchange; + + /** Time when coinapi first received trade from exchange */ + private final Instant time_coinapi; + + /** Our trade unique identifier in form of UUIDv4 */ + private final String uuid; + + /** Price of the transaction */ + private final double price; + + /** Base asset amount traded in the transaction */ + private final double size; + + /** Aggressor side of the transaction (BUY/SELL/BUY_ESTIMATED/SELL_ESTIMATED/UNKNOWN) */ + private final Taker_side taker_side; + + public Trade(String symbol_id, Instant time_exchange, Instant time_coinapi, String uuid, double price, double size, Taker_side taker_side) { + this.symbol_id = symbol_id; + this.time_exchange = time_exchange; + this.time_coinapi = time_coinapi; + this.uuid = uuid; + this.price = price; + this.size = size; + this.taker_side = taker_side; + } + + public String get_symbol_id() { + return symbol_id; + } + + public Instant get_time_exchange() { + return time_exchange; + } + + public Instant get_time_coinapi() { + return time_coinapi; + } + + public String get_uuid() { + return uuid; + } + + public double get_price() { + return price; + } + + public double get_size() { + return size; + } + + public Taker_side get_taker_side() { + return taker_side; + } + +} diff --git a/data-api/java-rest/src/main/java/io/coinapi/rest/UtilsJSON.java b/data-api/java-rest/src/main/java/io/coinapi/rest/UtilsJSON.java new file mode 100644 index 0000000000..c9599bed70 --- /dev/null +++ b/data-api/java-rest/src/main/java/io/coinapi/rest/UtilsJSON.java @@ -0,0 +1,81 @@ +package io.coinapi.rest; + +import org.json.JSONObject; + +import java.time.Instant; + +/** + * Helper class to handle the json. + */ +public class UtilsJSON { + + /** + * Converting json values to string. + * @param name + * @param value + * @return + */ + public static String parseStringFromJson(String name, JSONObject value) { + + if (value.has(name)) { + return value.getString(name); + } + return null; + } + + /** + * Converting json values to double. + * @param name + * @param value + * @return + */ + public static Double parseDoubleFromJson(String name, JSONObject value) { + + if (value.has(name)) { + return value.getDouble(name); + } + return null; + } + + /** + * Converting json values to boolean. + * @param name + * @param value + * @return + */ + public static Boolean parseBooleanFromJson(String name, JSONObject value) { + + if (value.has(name)) { + return value.getBoolean(name); + } + return null; + } + + /** + * Converting json values to instatnt. + * @param name + * @param value + * @return + */ + public static Instant parseInstantFromJson(String name, JSONObject value) { + + if (value.has(name)) { + return Instant.parse(value.getString(name)); + } + return null; + } + + /** + * Converting json values to integer. + * @param name + * @param value + * @return + */ + public static Integer parseIntegerFromJson(String name, JSONObject value) { + + if (value.has(name)) { + return value.getInt(name); + } + return null; + } +} diff --git a/data-api/java-rest/src/test/java/io/coinapi/rest/REST_methodsTest.java b/data-api/java-rest/src/test/java/io/coinapi/rest/REST_methodsTest.java new file mode 100644 index 0000000000..fc66049c2b --- /dev/null +++ b/data-api/java-rest/src/test/java/io/coinapi/rest/REST_methodsTest.java @@ -0,0 +1,882 @@ +package io.coinapi.rest; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.time.Instant; + +/** + * Unit test for REST_method. + */ +public class REST_methodsTest +{ + private static String COINAPI_KEY; + private REST_methods rm; + + @Before + public void configureCoinAPIKey() throws IOException { + + Config config = new Config(); + COINAPI_KEY = config.getPropValues("coinapi_key"); + if (COINAPI_KEY.equals("YOUR_API_KEY_HERE")) { + System.err.println( + "ERROR: REST_methods_test.main will abort because its constant COINAPI_KEY has the value \"" + COINAPI_KEY + "\"" + "\n" + + "Solution: edit the file REST_methods_test.java so that its COINAPI_KEY constant has your coinapi key, recompile, then run" + "\n" + ); + } + // NOTE: above each test method below is a URL that you can paste into your browser + // AFTER you change the "apikey=YOUR_API_KEY_HERE" text to have your actual coinapi key. + // You can compare by eyeball the results in the browser against what the methods below print out. + // +++ in the future: this eyeball comparison is bad, should automate the downloading of JSON from the URLs and then compare it against the Java methods below somehow. + // One problem is that the Java methods below do not print out the raw JSON text that the downloaded, instead they print out a highly processed versionof it. + rm = new REST_methods(COINAPI_KEY); + } + + /** + * https://rest.coinapi.io/v1/exchanges?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testMetadataListAllExchanges() throws IOException { + assertEquals(test_metadata_list_all_exchanges(rm), true); + } + + + /** + * https://rest.coinapi.io/v1/assets?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testMetadataListAllAssets() throws IOException { + assertEquals(test_metadata_list_all_assets(rm), true); + } + + /** + * https://rest.coinapi.io/v1/symbols?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testMetadataListAllSymbols() throws IOException { + assertEquals(test_metadata_list_all_symbols(rm), true); + } + + /** + * https://rest.coinapi.io/v1/exchangerate/BTC/USD?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testGetExchangeRate() throws IOException { + assertEquals(test_get_exchange_rate(rm, "BTC", "USD"), true); + } + + /** + * https://rest.coinapi.io/v1/exchangerate/BTC/USD?time=2016-11-01T22:08:41Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testGetExchangeRate2() throws IOException { + assertEquals(test_get_exchange_rate(rm, "BTC", "USD", Instant.parse("2016-11-01T22:08:41Z")), true); + } + + /** + * https://rest.coinapi.io/v1/exchangerate/BTC?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testGetAllExchangeRates() throws IOException { + assertEquals(test_get_all_exchange_rates(rm, "BTC"), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/periods?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvListAllPeriods() throws IOException { + assertEquals(test_ohlcv_list_all_periods(rm), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/latest?period_id=1MIN&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetLatestTimeseries() throws IOException { + assertEquals(test_ohlcv_get_latest_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/latest?period_id=1MIN&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetLatestTimeseries2() throws IOException { + assertEquals(test_ohlcv_get_latest_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN, 5), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-11-01T22:08:41Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetHistoricalTimeseries() throws IOException { + assertEquals(test_ohlcv_get_historical_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN, Instant.parse("2016-11-01T22:08:41Z")), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetHistoricalTimeseries2() throws IOException { + assertEquals(test_ohlcv_get_historical_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN, Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetHistoricalTimeseries3() throws IOException { + assertEquals(test_ohlcv_get_historical_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN, Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z")), true); + } + + /** + * https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history?period_id=1MIN&time_start=2016-11-01T22:08:41Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOhlcvGetHistoricalTimeseries4() throws IOException { + assertEquals(test_ohlcv_get_historical_timeseries(rm, "BITSTAMP_SPOT_BTC_USD", Period_identifier._1MIN, Instant.parse("2016-11-01T22:08:41Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/trades/latest?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetLatestData() throws IOException { + assertEquals(test_trades_get_latest_data(rm), true); + } + + /** + * https://rest.coinapi.io/v1/trades/latest?limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetLatestData2() throws IOException { + assertEquals(test_trades_get_latest_data(rm, 5), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/latest?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetLatestData3() throws IOException { + assertEquals(test_trades_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD"), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/latest?limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetLatestData4() throws IOException { + assertEquals(test_trades_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD", 5), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetHistoricalData() throws IOException { + assertEquals(test_trades_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z")), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetHistoricalData2() throws IOException { + assertEquals(test_trades_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetHistoricalData3() throws IOException { + assertEquals(test_trades_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z")), true); + } + + /** + * https://rest.coinapi.io/v1/trades/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testTradesGetHistoricalData4() throws IOException { + assertEquals(test_trades_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/current?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetForAllSymbols() throws IOException { + assertEquals(test_quotes_get_for_all_symbols(rm), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/current?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetForSymbol() throws IOException { + assertEquals(test_quotes_get_for_symbol(rm, "BITSTAMP_SPOT_BTC_USD"), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/latest?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetLatestData() throws IOException { + assertEquals(test_quotes_get_latest_data(rm), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/latest?limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetLatestData2() throws IOException { + assertEquals(test_quotes_get_latest_data(rm, 5), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/latest?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetLatestData3() throws IOException { + assertEquals(test_quotes_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD"), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/latest?limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetLatestData4() throws IOException { + assertEquals(test_quotes_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD", 5), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetHistoricalData() throws IOException { + assertEquals(test_quotes_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z")), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetHistoricalData2() throws IOException { + assertEquals(test_quotes_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetHistoricalData3() throws IOException { + assertEquals(test_quotes_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z")), true); + } + + /** + * https://rest.coinapi.io/v1/quotes/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testQuotesGetHistoricalData4() throws IOException { + assertEquals(test_quotes_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/current?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetForSymbol() throws IOException { + assertEquals(test_orderbooks_get_for_symbol(rm, "BITSTAMP_SPOT_BTC_USD"), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/latest?apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetLatestData() throws IOException { + assertEquals(test_orderbooks_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD"), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/latest?limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetLatestData2() throws IOException { + assertEquals(test_orderbooks_get_latest_data(rm, "BITSTAMP_SPOT_BTC_USD", 5), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetHistoricalData() throws IOException { + assertEquals(test_orderbooks_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z")), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetHistoricalData2() throws IOException { + assertEquals(test_orderbooks_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), 5), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetHistoricalData3() throws IOException { + assertEquals(test_orderbooks_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z")), true); + } + + /** + * https://rest.coinapi.io/v1/orderbooks/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-11-01T22:08:41Z&time_end=2016-11-02T10:24:07Z&limit=5&apikey=YOUR_API_KEY_HERE + */ + @Test + public void testOrderbooksGetHistoricalData4() throws IOException { + assertEquals(test_orderbooks_get_historical_data(rm, "BITSTAMP_SPOT_BTC_USD", Instant.parse("2016-11-01T22:08:41Z"), Instant.parse("2016-11-02T10:24:07Z"), 5), true); + } + + // -------------------- test_XXX methods -------------------- + + private boolean test_metadata_list_all_exchanges(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("list_all_exchanges() started"); + Exchange[] result = rm.list_all_exchanges(); + for (Exchange e : result) { + System.out.println(exchange_to_string(e)); + } + System.out.println("list_all_exchanges() finished"); + return true; + } + + + private boolean test_metadata_list_all_assets(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("list_all_assets() started"); + Asset[] result = rm.list_all_assets(); + for (Asset a : result) { + System.out.println(asset_to_string(a)); + } + System.out.println("list_all_assets() finished"); + return true; + } + + private boolean test_metadata_list_all_symbols(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("list_all_symbols() started"); + Symbol[] result = rm.list_all_symbols(); + for (Symbol s : result) { + System.out.println(symbol_to_string(s)); + } + System.out.println("list_all_symbols() finished"); + return true; + } + + private boolean test_get_exchange_rate(REST_methods rm, String asset_id_base, String asset_id_quote) throws IOException { + System.out.println(); + System.out.println("get_exchange_rate(asset_id_base, asset_id_quote) started"); + Exchange_rate result = rm.get_exchange_rate(asset_id_base, asset_id_quote); + System.out.println(exchange_rate_to_string(result)); + System.out.println("get_exchange_rate(asset_id_base, asset_id_quote) finished"); + return true; + } + + private boolean test_get_exchange_rate(REST_methods rm, String asset_id_base, String asset_id_quote, Instant time) throws IOException { + System.out.println(); + System.out.println("get_exchange_rate(asset_id_base, asset_id_quote, time) started"); + Exchange_rate result = rm.get_exchange_rate(asset_id_base, asset_id_quote, time); + System.out.println(exchange_rate_to_string(result)); + System.out.println("get_exchange_rate(asset_id_base, asset_id_quote, time) finished"); + return true; + } + + private boolean test_get_all_exchange_rates(REST_methods rm, String asset_id_base) throws IOException { + System.out.println(); + System.out.println("get_all_exchange_rates(asset_id_base) started"); + Exchange_rate[] result = rm.get_all_exchange_rates(asset_id_base); + for (Exchange_rate e : result) { + System.out.println(exchange_rate_to_string(e)); + } + System.out.println("get_all_exchange_rates(asset_id_base) finished"); + return true; + } + + private boolean test_ohlcv_list_all_periods(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("ohlcv_list_all_periods() started"); + Period[] result = rm.ohlcv_list_all_periods(); + for (Period p : result) { + System.out.println(period_to_string(p)); + } + System.out.println("ohlcv_list_all_periods() finished"); + return true; + } + + private boolean test_ohlcv_get_latest_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_latest_timeseries(symbol_id, period_id) started"); + Timedata[] result = rm.ohlcv_get_latest_timeseries(symbol_id, period_id); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_latest_timeseries(symbol_id, period_id) finished"); + return true; + } + + private boolean test_ohlcv_get_latest_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id, int limit) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_latest_timeseries(symbol_id, period_id, limit) started"); + Timedata[] result = rm.ohlcv_get_latest_timeseries(symbol_id, period_id, limit); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_latest_timeseries(symbol_id, period_id, limit) finished"); + return true; + } + + private boolean test_ohlcv_get_historical_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id, Instant time_start) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start) started"); + Timedata[] result = rm.ohlcv_get_historical_timeseries(symbol_id, period_id, time_start); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start) finished"); + return true; + } + + private boolean test_ohlcv_get_historical_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id, Instant time_start, Instant time_end) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end) started"); + Timedata[] result = rm.ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end) finished"); + return true; + } + + private boolean test_ohlcv_get_historical_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id, Instant time_start, int limit) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, limit) started"); + Timedata[] result = rm.ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, limit); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, limit) finished"); + return true; + } + + private boolean test_ohlcv_get_historical_timeseries(REST_methods rm, String symbol_id, Period_identifier period_id, Instant time_start, Instant time_end, int limit) throws IOException { + System.out.println(); + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end, limit) started"); + Timedata[] result = rm.ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end, limit); + for (Timedata t : result) { + System.out.println(timedata_to_string(t)); + } + System.out.println("ohlcv_get_historical_timeseries(symbol_id, period_id, time_start, time_end, limit) finished"); + return true; + } + + private boolean test_trades_get_latest_data(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("trades_get_latest_data() started"); + Trade[] result = rm.trades_get_latest_data(); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_latest_data() finished"); + return true; + } + + private boolean test_trades_get_latest_data(REST_methods rm, int limit) throws IOException { + System.out.println(); + System.out.println("trades_get_latest_data(limit) started"); + Trade[] result = rm.trades_get_latest_data(limit); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_latest_data(limit) finished"); + return true; + } + + private boolean test_trades_get_latest_data(REST_methods rm, String symbol_id) throws IOException { + System.out.println(); + System.out.println("trades_get_latest_data(symbol_id) started"); + Trade[] result = rm.trades_get_latest_data(symbol_id); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_latest_data(symbol_id) finished"); + return true; + } + + private boolean test_trades_get_latest_data(REST_methods rm, String symbol_id, int limit) throws IOException { + System.out.println(); + System.out.println("trades_get_latest_data(symbol_id, limit) started"); + Trade[] result = rm.trades_get_latest_data(symbol_id, limit); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_latest_data(symbol_id, limit) finished"); + return true; + } + + private boolean test_trades_get_historical_data(REST_methods rm, String symbol_id, Instant start_time) throws IOException { + System.out.println(); + System.out.println("trades_get_historical_data(symbol_id, start_time) started"); + Trade[] result = rm.trades_get_historical_data(symbol_id, start_time); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_historical_data(symbol_id, start_time) finished"); + return true; + } + + private boolean test_trades_get_historical_data(REST_methods rm, String symbol_id, Instant start_time, int limit) throws IOException { + System.out.println(); + System.out.println("trades_get_historical_data(symbol_id, start_time, limit) started"); + Trade[] result = rm.trades_get_historical_data(symbol_id, start_time, limit); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_historical_data(symbol_id, start_time, limit) finished"); + return true; + } + + private boolean test_trades_get_historical_data(REST_methods rm, String symbol_id, Instant start_time, Instant end_time) throws IOException { + System.out.println(); + System.out.println("trades_get_historical_data(symbol_id, start_time, end_time) started"); + Trade[] result = rm.trades_get_historical_data(symbol_id, start_time, end_time); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_historical_data(symbol_id, start_time, end_time) finished"); + return true; + } + + private boolean test_trades_get_historical_data(REST_methods rm, String symbol_id, Instant start_time, Instant end_time, int limit) throws IOException { + System.out.println(); + System.out.println("trades_get_historical_data(symbol_id, start_time, end_time, limit) started"); + Trade[] result = rm.trades_get_historical_data(symbol_id, start_time, end_time, limit); + for (Trade t : result) { + System.out.println(trade_to_string(t)); + } + System.out.println("trades_get_historical_data(symbol_id, start_time, end_time, limit) finished"); + return true; + } + + private boolean test_quotes_get_for_all_symbols(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("quotes_get_for_all_symbols() started"); + Quote_with_trade[] result = rm.quotes_get_for_all_symbols(); + for (Quote_with_trade t : result) { + System.out.println(quote_with_trade_to_string(t)); + } + System.out.println("quotes_get_for_all_symbols() finished"); + return true; + } + + private boolean test_quotes_get_for_symbol(REST_methods rm, String symbol_id) throws IOException { + System.out.println(); + System.out.println("quotes_get_for_symbol(symbol_id) started"); + Quote_with_trade result = rm.quotes_get_for_symbol(symbol_id); + System.out.println(quote_with_trade_to_string(result)); + System.out.println("quotes_get_for_symbol(symbol_id) finished"); + return true; + } + + private boolean test_quotes_get_latest_data(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("quotes_get_latest_data() started"); + Quote[] result = rm.quotes_get_latest_data(); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_latest_data() finished"); + return true; + } + + private boolean test_quotes_get_latest_data(REST_methods rm, int limit) throws IOException { + System.out.println(); + System.out.println("quotes_get_latest_data(limit) started"); + Quote[] result = rm.quotes_get_latest_data(limit); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_latest_data(limit) finished"); + return true; + } + + private boolean test_quotes_get_latest_data(REST_methods rm, String symbol_id) throws IOException { + System.out.println(); + System.out.println("quotes_get_latest_data(symbol_id) started"); + Quote[] result = rm.quotes_get_latest_data(symbol_id); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_latest_data(symbol_id) finished"); + return true; + } + + private boolean test_quotes_get_latest_data(REST_methods rm, String symbol_id, int limit) throws IOException { + System.out.println(); + System.out.println("quotes_get_latest_data(symbol_id, limit) started"); + Quote[] result = rm.quotes_get_latest_data(symbol_id, limit); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_latest_data(symbol_id, limit) finished"); + return true; + } + + private boolean test_quotes_get_historical_data(REST_methods rm, String symbol_id, Instant time_start) throws IOException { + System.out.println(); + System.out.println("quotes_get_historical_data(symbol_id, time_start) started"); + Quote[] result = rm.quotes_get_historical_data(symbol_id, time_start); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_historical_data(symbol_id, time_start) finished"); + return true; + } + + private boolean test_quotes_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, int limit) throws IOException { + System.out.println(); + System.out.println("quotes_get_historical_data(symbol_id, time_start, limit) started"); + Quote[] result = rm.quotes_get_historical_data(symbol_id, time_start, limit); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_historical_data(symbol_id, time_start, limit) finished"); + return true; + } + + private boolean test_quotes_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, Instant time_end) throws IOException { + System.out.println(); + System.out.println("quotes_get_historical_data(symbol_id, time_start, time_end) started"); + Quote[] result = rm.quotes_get_historical_data(symbol_id, time_start, time_end); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_historical_data(symbol_id, time_start, time_end) finished"); + return true; + } + + private boolean test_quotes_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, Instant time_end, int limit) throws IOException { + System.out.println(); + System.out.println("quotes_get_historical_data(symbol_id, time_start, time_end, limit) started"); + Quote[] result = rm.quotes_get_historical_data(symbol_id, time_start, time_end, limit); + for (Quote t : result) { + System.out.println(quote_to_string(t)); + } + System.out.println("quotes_get_historical_data(symbol_id, time_start, time_end, limit) finished"); + return true; + } + + private boolean test_orderbooks_get_for_all_symbols(REST_methods rm) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_for_all_symbols() started"); + Orderbook[] result = rm.orderbooks_get_for_all_symbols(); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_for_all_symbols() finished"); + return true; + } + + private boolean test_orderbooks_get_for_symbol(REST_methods rm, String symbol_id) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_for_symbol(symbol_id) started"); + Orderbook result = rm.orderbooks_get_for_symbol(symbol_id); + System.out.println(orderbook_to_string(result)); + System.out.println("orderbooks_get_for_symbol(symbol_id) finished"); + return true; + } + + private boolean test_orderbooks_get_latest_data(REST_methods rm, String symbol_id) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_latest_data(symbol_id) started"); + Orderbook[] result = rm.orderbooks_get_latest_data(symbol_id); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_latest_data(symbol_id) finished"); + return true; + } + + private boolean test_orderbooks_get_latest_data(REST_methods rm, String symbol_id, int limit) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_latest_data(symbol_id, limit) started"); + Orderbook[] result = rm.orderbooks_get_latest_data(symbol_id, limit); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_latest_data(symbol_id, limit) finished"); + return true; + } + + private boolean test_orderbooks_get_historical_data(REST_methods rm, String symbol_id, Instant time_start) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_historical_data(symbol_id, time_start) started"); + Orderbook[] result = rm.orderbooks_get_historical_data(symbol_id, time_start); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_historical_data(symbol_id, time_start) finished"); + return true; + } + + private boolean test_orderbooks_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, int limit) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, limit) started"); + Orderbook[] result = rm.orderbooks_get_historical_data(symbol_id, time_start, limit); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, limit) finished"); + return true; + } + + private boolean test_orderbooks_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, Instant time_end) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, time_end) started"); + Orderbook[] result = rm.orderbooks_get_historical_data(symbol_id, time_start, time_end); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, time_end) finished"); + return true; + } + + private boolean test_orderbooks_get_historical_data(REST_methods rm, String symbol_id, Instant time_start, Instant time_end, int limit) throws IOException { + System.out.println(); + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, time_end, limit) started"); + Orderbook[] result = rm.orderbooks_get_historical_data(symbol_id, time_start, time_end, limit); + for (Orderbook o : result) { + System.out.println(orderbook_to_string(o)); + } + System.out.println("orderbooks_get_historical_data(symbol_id, time_start, time_end, limit) finished"); + return true; + } + + // -------------------- XXX_to_string methods -------------------- + + // +++ all of these methods should be put into toString methods of the respective classes? + + private String asset_to_string(Asset a) { + if (a.get_name() != null) { + return String.format("Asset (name = %s, id = %s, cryptocurrency = %s)", a.get_name(), a.get_asset_id(), a.is_type_crypto() ? "yes" : "no"); + } else { + return String.format("Asset (null name, id = %s, cryptocurrency = %s)", a.get_asset_id(), a.is_type_crypto() ? "yes" : "no"); + } + } + + private String exchange_to_string(Exchange e) { + return String.format("Exchange (name = %s, id = %s, website = %s)", e.get_name(), e.get_exchange_id(), e.get_website()); + } + + private String symbol_to_string(Symbol s) { + String result = ""; + String additional = ""; + + switch (s.get_symbol_type()) { + case SymbolType.SPOT: + result += "SPOT symbol"; + break; + case SymbolType.FUTURES: + result += "FUTURES symbol "; + additional += "\n Delivery date: " + s.get_future_delivery_time().toString(); + break; + case SymbolType.OPTION: + result += "OPTION symbol "; + additional += "\n Type of option: " + (s.get_is_option_type_is_call() ? "Call" : "Put") + ", "; + additional += "Strike price: " + s.get_option_strike_price() + ", "; + additional += "Conract Unit: " + s.get_option_contract_unit(); + + if (s.get_option_exercise_style().equals(OptionExerciseStyle.EUROPEAN)) + additional += "\n EUROPEAN exercise style"; + if (s.get_option_exercise_style().equals(OptionExerciseStyle.AMERICAN)) + additional += "\n AMERICAN exercise style"; + additional += "\n Expiration time: " + s.get_option_expiration_time(); + case SymbolType.INDEX: + result += "INDEX symbol"; + break; + case SymbolType.PERPETUAL: + result += "PERPETUAL symbol"; + break; + default: + result += "Invalid symbol "; + break; + } + + + result += "(symbol_id = " + s.get_symbol_id(); + result += ", exchange_id = " + s.get_exchange_id(); + result += ", " + s.get_asset_id_base() + "/" + s.get_asset_id_quote() + ")"; + + return result + additional; + } + + private String exchange_rate_to_string(Exchange_rate e) { + return String.format("Exchange_rate for %s/%s at %s is %.7f", e.get_asset_id_base(), e.get_asset_id_quote(), e.get_time().toString(), e.get_rate()); + } + + private String period_to_string(Period p) { + return String.format("Period (seconds = %d, months = %d, unit count = %d, unit_name = %s), display name: %s", + p.get_length_seconds(), p.get_length_months(), p.get_unit_count(), p.get_unit_name(), p.get_display_name()); + } + + private String timedata_to_string(Timedata t) { + return String.format("Timedata (start: %s, end: %s, open: %s, close: %s)\n Price (open: %.2f, low: %.2f, high: %.2f: close: %.2f)\n common.Trade (Volume: %.7f, Count: %d)", + t.get_time_period_start().toString(), t.get_time_period_end().toString(), t.get_time_open().toString(), t.get_time_close().toString(), + t.get_price_open(), t.get_price_low(), t.get_price_high(), t.get_price_close(), t.get_volume_traded(), t.get_trades_count()); + } + + private String trade_to_string(Trade t) { + return String.format("Trade (symbol = %s, exchange time = %s, CoinAPI time: %s)\n UUID = %s, price = %.2f, size = %.6f, taker side: %s", + t.get_symbol_id(), t.get_time_exchange(), t.get_time_coinapi(), t.get_uuid(), t.get_price(), t.get_size(), t.get_taker_side().toString()); + } + + private String quote_with_trade_to_string(Quote_with_trade q) { + if (q.has_last_trade()) { + return String.format("Quote_with_trade (symbol = %s, exchange time = %s, CoinAPI time: %s)\n ask (Price = %.2f, Size = %.6f)\n bid (Price = %.2f, Size = %.6f)\n Last %s", + q.get_symbol_id(), q.get_time_exchange(), q.get_time_coinapi(), q.get_ask_price(), q.get_ask_size(), q.get_bid_price(), q.get_bid_size(), + trade_to_string(q.get_last_trade())); + } else { + return String.format("Quote_with_trade (symbol = %s, exchange time = %s, CoinAPI time: %s)\n ask (Price = %.2f, Size = %.6f)\n bid (Price = %.2f, Size = %.6f)", + q.get_symbol_id(), q.get_time_exchange(), q.get_time_coinapi(), q.get_ask_price(), q.get_ask_size(), q.get_bid_price(), q.get_bid_size()); + } + } + + private String quote_to_string(Quote q) { + return String.format("Quote (symbol = %s, exchange time = %s, CoinAPI time: %s)\n ask (Price = %.2f, Size = %.6f)\n bid (Price = %.2f, Size = %.6f)", + q.get_symbol_id(), q.get_time_exchange(), q.get_time_coinapi(), q.get_ask_price(), q.get_ask_size(), q.get_bid_price(), q.get_bid_size()); + } + + private String asks_to_string(Orderbook o) { + String result = ""; + for (int i = 0; i < o.get_asks_count(); i++) { + result += String.format("\n ask (price = %.2f, size = %.6f)", o.get_ask(i).get_price(), o.get_ask(i).get_size()); + } + return result; + } + + private String bids_to_string(Orderbook o) { + String result = ""; + for (int i = 0; i < o.get_bids_count(); i++) { + result += String.format("\n bid (price = %.2f, size = %.6f)", o.get_bid(i).get_price(), o.get_bid(i).get_size()); + } + return result; + } + + private String orderbook_to_string(Orderbook o) { + return String.format("Orderbook (symbol = %s, exchange time = %s, CoinAPI time: %s)\n Asks:%s\n Bids:%s", + o.get_symbol_id(), o.get_time_exchange(), o.get_time_coinapi(), asks_to_string(o), bids_to_string(o) + ); + } +} diff --git a/data-api/java-websocket/README.md b/data-api/java-websocket/README.md new file mode 100644 index 0000000000..a385b7910e --- /dev/null +++ b/data-api/java-websocket/README.md @@ -0,0 +1,28 @@ +## Usage + +```java +CoinAPIWebSocket coinAPIWebSocket = new CoinAPIWebSocketImpl(true); + +// create hello message +Hello hello = new Hello(); +hello.setApiKey(apiKey); +hello.setSubscribeDataType(new String[]{"trade"}); + +// definition of a method that processes inbound data +coinAPIWebSocket.setTradesInvoke(message -> { + Trades trades = (Trades) message; + System.out.println(trades.getUuid()); +}); + +// definition of a method that processes errors +coinAPIWebSocket.setErrorInvoke(message -> { + Error error = (Error) message; + System.out.println(error.getMessage()); +}); + +// open a websocket connection +coinAPIWebSocket.sendHelloMessage(hello); + +// close connection +coinAPIWebSocket.closeConnect(); +``` \ No newline at end of file diff --git a/data-api/java-websocket/deploy.sh b/data-api/java-websocket/deploy.sh new file mode 100644 index 0000000000..b9c4ff8b0f --- /dev/null +++ b/data-api/java-websocket/deploy.sh @@ -0,0 +1,2 @@ +#!/bin/bash +mvn clean javadoc:jar deploy -Dmaven.test.skip=true -P release-sign-artifacts diff --git a/data-api/java-websocket/pom.xml b/data-api/java-websocket/pom.xml new file mode 100644 index 0000000000..1cc2d3d2d0 --- /dev/null +++ b/data-api/java-websocket/pom.xml @@ -0,0 +1,215 @@ + + + 4.0.0 + + io.coinapi.websocket + v1 + 1.8 + + + COINAPI LTD + https://www.CoinAPI.io + + + + + MIT License + MIT License + + + + + + github + coinapi.websocket.v1 + https://maven.pkg.github.com/coinapi/coinapi-sdk + + + + coinapi.websocket.v1 + https://docs.coinapi.io + Java SDK for CoinAPI + + + tprzybysz + Tomasz Przybysz + tom.przybysz@gmail.com + + developer + + + + + + UTF-8 + 1.8 + 1.8 + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + default-deploy + deploy + + deploy + + + + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + maven-assembly-plugin + 2.6 + + + jar-with-dependencies + + + + + make-assembly + package + + attached + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + private + true + + + + attach-javadocs + deploy + + jar + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-sources + + jar + + + + attach-javadoc + + jar + + + + + + + + + + + + com.dslplatform + dsl-json-java8 + 1.9.3 + + + jakarta.websocket + jakarta.websocket-api + 2.0.0 + + + org.glassfish.tyrus.ext + tyrus-client-java8 + 2.0.0 + + + org.glassfish.tyrus + tyrus-container-grizzly-client + 2.0.0 + + + junit + junit + 4.13.1 + test + + + diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocket.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocket.java new file mode 100644 index 0000000000..dd016578ed --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocket.java @@ -0,0 +1,20 @@ +package io.coinapi.websocket; + +import io.coinapi.websocket.interfaces.InvokeFunction; +import io.coinapi.websocket.model.Hello; + +import java.io.IOException; + +public interface CoinAPIWebSocket { + + void sendHelloMessage(Hello hello) throws IOException; + void closeConnect() throws IOException; + + void setTradesInvoke(InvokeFunction function); + void setQuotesInvoke(InvokeFunction function); + void setBookInvoke(InvokeFunction function); + void setOHLCVInvoke(InvokeFunction function); + void setVolumeInvoke(InvokeFunction function); + void setErrorInvoke(InvokeFunction function); + void setReconnectInvoke(InvokeFunction function); +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocketImpl.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocketImpl.java new file mode 100644 index 0000000000..6a239adb6a --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/CoinAPIWebSocketImpl.java @@ -0,0 +1,248 @@ +package io.coinapi.websocket; + +import com.dslplatform.json.DslJson; +import io.coinapi.websocket.communication.WebsocketReconnectHandler; +import io.coinapi.websocket.exception.NotImplementedException; +import io.coinapi.websocket.interfaces.InvokeFunction; +import io.coinapi.websocket.model.*; +import io.coinapi.websocket.model.Error; +import org.glassfish.tyrus.client.ClientManager; + +import jakarta.websocket.*; +import org.glassfish.tyrus.client.ClientProperties; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.Optional; +import java.util.Queue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; + +public class CoinAPIWebSocketImpl implements CoinAPIWebSocket { + + private final String sandboxUrl = "wss://ws-sandbox.coinapi.io/v1/"; + private final String noSandboxUrl = "wss://ws.coinapi.io/v1/"; + + private Boolean isSandbox; + private DslJson json = new DslJson<>(); + + private static CountDownLatch latch; + private ClientManager client; + private Optional connection = Optional.empty(); + private Optional processingMessages; + private volatile boolean running = true; + + private Queue messagesQueue = new LinkedBlockingDeque(); + + private InvokeFunction tradesInvoke; + private InvokeFunction quotesInvoke; + private InvokeFunction bookInvoke; + private InvokeFunction ohlcvInvoke; + private InvokeFunction volumeInvoke; + private InvokeFunction errorInvoke; + private InvokeFunction reconnectInvoke; + + /** + * + * @param isSandbox + */ + public CoinAPIWebSocketImpl(Boolean isSandbox) { + + this.isSandbox = isSandbox; + client = ClientManager.createClient(); + client.getProperties().put(ClientProperties.RECONNECT_HANDLER, new WebsocketReconnectHandler()); + + Runnable task = () -> { + while (running) { + if (messagesQueue.size() > 0) { + String message = (String) messagesQueue.remove(); + InputStream stream = new ByteArrayInputStream(message.getBytes()); + try { + MessageBase type = json.deserialize(MessageBase.class, stream); + MessageTypeEnum messageType = MessageTypeEnum.valueOf(type.getType()); + switch (messageType) { + case trade: + handle(message, Trades.class, tradesInvoke); + break; + case quote: + handle(message, Quotes.class, quotesInvoke); + break; + case book: + case book5: + case book20: + case book50: + handle(message, Book.class, bookInvoke); + break; + case ohlcv: + handle(message, OHLCV.class, ohlcvInvoke); + break; + case volume: + handle(message, Volume.class, volumeInvoke); + break; + case error: + handle(message, Error.class, errorInvoke); + break; + case reconnect: + handle(message, Reconnect.class, reconnectInvoke); + break; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }; + processingMessages = Optional.of(new Thread(task)); + } + + /** + * + * @param hello + * @throws IOException + */ + @Override + public void sendHelloMessage(Hello hello) throws IOException { + + processingMessages.get().start(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + json.serialize(hello, os); + + try { + latch = new CountDownLatch(1); + + final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); + + Endpoint endpoint = new Endpoint() { + @Override + public void onOpen(Session session, EndpointConfig config) { + try { + session.addMessageHandler(new MessageHandler.Whole() { + + @Override + public void onMessage(String message) { + messagesQueue.add(message); + latch.countDown(); + } + }); + session.getBasicRemote().sendText(os.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void onClose(Session session, CloseReason closeReason) { + super.onClose(session, closeReason); + } + }; + + connection = Optional.ofNullable(client.connectToServer(endpoint, cec, new URI(isSandbox ? sandboxUrl : noSandboxUrl))); + latch.await(100, TimeUnit.SECONDS); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * + * @throws IOException + */ + @Override + public void closeConnect() throws IOException { + + if (connection.isPresent()) { + connection.get().close(); + System.out.println("websocket connection closed"); + } + + if (processingMessages.isPresent() && processingMessages.get().isAlive()) { + running = false; + processingMessages.get().interrupt(); + System.out.println("processingMessage thread interrupt"); + } + } + + /** + * + * @param function + */ + @Override + public void setTradesInvoke(InvokeFunction function) { + this.tradesInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setQuotesInvoke(InvokeFunction function) { + this.quotesInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setBookInvoke(InvokeFunction function) { + this.bookInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setOHLCVInvoke(InvokeFunction function) { + this.ohlcvInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setVolumeInvoke(InvokeFunction function) { + this.volumeInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setErrorInvoke(InvokeFunction function) { + this.errorInvoke = function; + } + + /** + * + * @param function + */ + @Override + public void setReconnectInvoke(InvokeFunction function) { + this.reconnectInvoke = function; + } + + private void handle(String message, Class deserializeClass, InvokeFunction invokeFunction) throws IOException, NotImplementedException { + + Object deserialize = json.deserialize(deserializeClass, new ByteArrayInputStream(message.getBytes())); + + if (invokeFunction == null) { + return; + } + invokeFunction.preprocesMessages((MessageBase) deserialize); + } + + @Override + protected final void finalize() throws Throwable { + super.finalize(); + closeConnect(); + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/communication/WebsocketReconnectHandler.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/communication/WebsocketReconnectHandler.java new file mode 100644 index 0000000000..8c297ffd97 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/communication/WebsocketReconnectHandler.java @@ -0,0 +1,33 @@ +package io.coinapi.websocket.communication; + +import jakarta.websocket.CloseReason; +import org.glassfish.tyrus.client.ClientManager; + +public class WebsocketReconnectHandler extends ClientManager.ReconnectHandler { + + @Override + public boolean onDisconnect(CloseReason closeReason) { + System.out.println("The connection has been closed (Code: {" + closeReason.getCloseCode() + "}, Reason: {" + + closeReason.getReasonPhrase() + "})."); + + if (closeReason.getCloseCode().equals(CloseReason.CloseCodes.CANNOT_ACCEPT)) { + return false; + } + return true; + } + + @Override + public boolean onConnectFailure(Exception exception) { + System.out.println("The connection has been closed due to a failure."); + System.out.println("Reason: " + exception); + + // Do not reconnect in case of failure. The CommunicationHandler will + // take care of changing the node and establishing a new connection. + return false; + } + + @Override + public long getDelay() { + return 5L; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/exception/NotImplementedException.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/exception/NotImplementedException.java new file mode 100644 index 0000000000..bf83b7f49f --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/exception/NotImplementedException.java @@ -0,0 +1,8 @@ +package io.coinapi.websocket.exception; + +public class NotImplementedException extends Exception { + + public NotImplementedException() { + super("Method not initialized"); + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/interfaces/InvokeFunction.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/interfaces/InvokeFunction.java new file mode 100644 index 0000000000..692ef0c248 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/interfaces/InvokeFunction.java @@ -0,0 +1,9 @@ +package io.coinapi.websocket.interfaces; + +import io.coinapi.websocket.model.MessageBase; + +@FunctionalInterface +public interface InvokeFunction { + + void preprocesMessages(MessageBase message); +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Asks.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Asks.java new file mode 100644 index 0000000000..03326ffbb1 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Asks.java @@ -0,0 +1,7 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; + +@CompiledJson +public class Asks extends Data { +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Bids.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Bids.java new file mode 100644 index 0000000000..ceeee418f0 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Bids.java @@ -0,0 +1,7 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; + +@CompiledJson +public class Bids extends Data { +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Book.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Book.java new file mode 100644 index 0000000000..02d29e784d --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Book.java @@ -0,0 +1,79 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; +import java.util.List; + +@CompiledJson +public class Book extends MessageBase { + + private String symbolId; + private Integer sequence; + private OffsetDateTime timeExchange; + private OffsetDateTime timeCoinApi; + private String isSnapshot = "true"; + private List asks; + private List bids; + + public String getSymbolId() { + return symbolId; + } + + @JsonAttribute(name = "symbol_id") + public void setSymbolId(String symbolId) { + this.symbolId = symbolId; + } + + public Integer getSequence() { + return sequence; + } + + public void setSequence(Integer sequence) { + this.sequence = sequence; + } + + public OffsetDateTime getTimeExchange() { + return timeExchange; + } + + @JsonAttribute(name = "time_exchange") + public void setTimeExchange(OffsetDateTime timeExchange) { + this.timeExchange = timeExchange; + } + + public OffsetDateTime getTimeCoinApi() { + return timeCoinApi; + } + + @JsonAttribute(name = "time_coinapi") + public void setTimeCoinApi(OffsetDateTime timeCoinApi) { + this.timeCoinApi = timeCoinApi; + } + + public Boolean getSnapshot() { + return isSnapshot.equalsIgnoreCase("true"); + } + + @JsonAttribute(name = "is_snapshot") + public void setSnapshot(String snapshot) { + isSnapshot = snapshot; + } + + public List getAsks() { + return asks; + } + + public void setAsks(List asks) { + this.asks = asks; + } + + public List getBids() { + return bids; + } + + public void setBids(List bids) { + this.bids = bids; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Data.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Data.java new file mode 100644 index 0000000000..887db8e9ca --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Data.java @@ -0,0 +1,23 @@ +package io.coinapi.websocket.model; + +public class Data { + + private Double price; + private Double size; + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + + public Double getSize() { + return size; + } + + public void setSize(Double size) { + this.size = size; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Error.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Error.java new file mode 100644 index 0000000000..4b33875cd2 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Error.java @@ -0,0 +1,14 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +@CompiledJson +public class Error extends MessageBase { + private String message; + + public String getMessage() { return message; } + + @JsonAttribute(name = "message") + public void setMessage(String message) { this.message = message; } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Hello.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Hello.java new file mode 100644 index 0000000000..99c9c42f28 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Hello.java @@ -0,0 +1,102 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +@CompiledJson +public class Hello { + + private String type = "hello"; + private String apikey; + private Boolean heartbeat = true; + private String[] subscribeDataType; + private String[] subscribeFilterSymbolId; + private String[] subscribeFilterAssetId; + private String[] subscribeFilterPeriodId; + private String[] subscribeFilterExchangeId; + private Integer subscribeUpdateLimitMsQuote; + private Integer subscribeUpdateLimitMsBookSnapshot; + + public String getType() { + return type; + } + + public String getApikey() { + return apikey; + } + + public Boolean getHeartbeat() { + return heartbeat; + } + + @JsonAttribute(name = "subscribe_data_type") + public String[] getSubscribeDataType() { + return subscribeDataType; + } + + @JsonAttribute(name = "subscribe_filter_symbol_id") + public String[] getSubscribeFilterSymbolId() { + return subscribeFilterSymbolId; + } + + @JsonAttribute(name = "subscribe_filter_asset_id") + public String[] getSubscribeFilterAssetId() { + return subscribeFilterAssetId; + } + + @JsonAttribute(name = "subscribe_filter_period_id") + public String[] getSubscribeFilterPeriodId() { + return subscribeFilterPeriodId; + } + + @JsonAttribute(name = "subscribe_filter_exchange_id") + public String[] getSubscribeFilterExchangeId() { + return subscribeFilterExchangeId; + } + + @JsonAttribute(name = "subscribe_update_limit_ms_quote") + public Integer getSubscribeUpdateLimitMsQuote() { + return subscribeUpdateLimitMsQuote; + } + + @JsonAttribute(name = "subscribe_update_limit_ms_book_snapshot") + public Integer getSubscribeUpdateLimitMsBookSnapshot() { + return subscribeUpdateLimitMsBookSnapshot; + } + + public void setApikey(String apikey) { + this.apikey = apikey; + } + + public void setHeartbeat(Boolean heartbeat) { + this.heartbeat = heartbeat; + } + + public void setSubscribeDataType(String[] subscribeDataType) { + this.subscribeDataType = subscribeDataType; + } + + public void setSubscribeFilterSymbolId(String[] subscribeFilterSymbolId) { + this.subscribeFilterSymbolId = subscribeFilterSymbolId; + } + + public void setSubscribeFilterAssetId(String[] subscribeFilterAssetId) { + this.subscribeFilterAssetId = subscribeFilterAssetId; + } + + public void setSubscribeFilterPeriodId(String[] subscribeFilterPeriodId) { + this.subscribeFilterPeriodId = subscribeFilterPeriodId; + } + + public void setSubscribeFilterExchangeId(String[] subscribeFilterExchangeId) { + this.subscribeFilterExchangeId = subscribeFilterExchangeId; + } + + public void setSubscribeUpdateLimitMsQuote(Integer subscribeUpdateLimitMsQuote) { + this.subscribeUpdateLimitMsQuote = subscribeUpdateLimitMsQuote; + } + + public void setSubscribeUpdateLimitMsBookSnapshot(Integer subscribeUpdateLimitMsBookSnapshot) { + this.subscribeUpdateLimitMsBookSnapshot = subscribeUpdateLimitMsBookSnapshot; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageBase.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageBase.java new file mode 100644 index 0000000000..580d57d875 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageBase.java @@ -0,0 +1,17 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; + +@CompiledJson +public class MessageBase { + + protected String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageTypeEnum.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageTypeEnum.java new file mode 100644 index 0000000000..c5356ee31d --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/MessageTypeEnum.java @@ -0,0 +1,15 @@ +package io.coinapi.websocket.model; + +public enum MessageTypeEnum { + trade, + quote, + book, + book5, + book20, + book50, + ohlcv, + volume, + hearbeat, + error, + reconnect +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/OHLCV.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/OHLCV.java new file mode 100644 index 0000000000..c7ee4b839a --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/OHLCV.java @@ -0,0 +1,140 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; + +@CompiledJson +public class OHLCV extends MessageBase { + + private String symbolId; + private Integer sequence; + private String periodId; + private OffsetDateTime timePeriodStart; + private OffsetDateTime timePeriodEnd; + private OffsetDateTime timeOpen; + private OffsetDateTime timeClose; + private Double priceOpen; + private Double priceHigh; + private Double priceLow; + private Double priceClose; + private Double volumeTraded; + private Integer tradesCount; + + public String getSymbolId() { + return symbolId; + } + + @JsonAttribute(name = "symbol_id") + public void setSymbolId(String symbolId) { + this.symbolId = symbolId; + } + + public Integer getSequence() { + return sequence; + } + + public void setSequence(Integer sequence) { + this.sequence = sequence; + } + + public String getPeriodId() { + return periodId; + } + + @JsonAttribute(name = "period_id") + public void setPeriodId(String periodId) { + this.periodId = periodId; + } + + public OffsetDateTime getTimePeriodStart() { + return timePeriodStart; + } + + @JsonAttribute(name = "time_period_start") + public void setTimePeriodStart(OffsetDateTime timePeriodStart) { + this.timePeriodStart = timePeriodStart; + } + + public OffsetDateTime getTimePeriodEnd() { + return timePeriodEnd; + } + + @JsonAttribute(name = "time_period_end") + public void setTimePeriodEnd(OffsetDateTime timePeriodEnd) { + this.timePeriodEnd = timePeriodEnd; + } + + public OffsetDateTime getTimeOpen() { + return timeOpen; + } + + @JsonAttribute(name = "time_open") + public void setTimeOpen(OffsetDateTime timeOpen) { + this.timeOpen = timeOpen; + } + + public OffsetDateTime getTimeClose() { + return timeClose; + } + + @JsonAttribute(name = "time_close") + public void setTimeClose(OffsetDateTime timeClose) { + this.timeClose = timeClose; + } + + public Double getPriceOpen() { + return priceOpen; + } + + @JsonAttribute(name = "price_open") + public void setPriceOpen(Double priceOpen) { + this.priceOpen = priceOpen; + } + + public Double getPriceHigh() { + return priceHigh; + } + + @JsonAttribute(name = "price_high") + public void setPriceHigh(Double priceHigh) { + this.priceHigh = priceHigh; + } + + public Double getPriceLow() { + return priceLow; + } + + @JsonAttribute(name = "price_low") + public void setPriceLow(Double priceLow) { + this.priceLow = priceLow; + } + + public Double getPriceClose() { + return priceClose; + } + + @JsonAttribute(name = "price_close") + public void setPriceClose(Double priceClose) { + this.priceClose = priceClose; + } + + public Double getVolumeTraded() { + return volumeTraded; + } + + @JsonAttribute(name = "volume_traded") + public void setVolumeTraded(Double volumeTraded) { + this.volumeTraded = volumeTraded; + } + + public Integer getTradesCount() { + return tradesCount; + } + + @JsonAttribute(name = "trades_count") + public void setTradesCount(Integer tradesCount) { + this.tradesCount = tradesCount; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Quotes.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Quotes.java new file mode 100644 index 0000000000..d33f7def73 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Quotes.java @@ -0,0 +1,90 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; + +@CompiledJson +public class Quotes extends MessageBase { + + private String symbolId; + private Integer sequence; + private OffsetDateTime timeExchange; + private OffsetDateTime timeCoinApi; + private Double askPrice; + private Double askSize; + private Double bidPrice; + private Double bidSize; + + public String getSymbolId() { + return symbolId; + } + + @JsonAttribute(name = "symbol_id") + public void setSymbolId(String symbolId) { + this.symbolId = symbolId; + } + + public Integer getSequence() { + return sequence; + } + + public void setSequence(Integer sequence) { + this.sequence = sequence; + } + + public OffsetDateTime getTimeExchange() { + return timeExchange; + } + + @JsonAttribute(name = "time_exchange") + public void setTimeExchange(OffsetDateTime timeExchange) { + this.timeExchange = timeExchange; + } + + public OffsetDateTime getTimeCoinApi() { + return timeCoinApi; + } + + @JsonAttribute(name = "time_coinapi") + public void setTimeCoinApi(OffsetDateTime timeCoinApi) { + this.timeCoinApi = timeCoinApi; + } + + public Double getAskPrice() { + return askPrice; + } + + @JsonAttribute(name = "ask_price") + public void setAskPrice(Double askPrice) { + this.askPrice = askPrice; + } + + public Double getAskSize() { + return askSize; + } + + @JsonAttribute(name = "ask_size") + public void setAskSize(Double askSize) { + this.askSize = askSize; + } + + public Double getBidPrice() { + return bidPrice; + } + + @JsonAttribute(name = "bid_price") + public void setBidPrice(Double bidPrice) { + this.bidPrice = bidPrice; + } + + public Double getBidSize() { + return bidSize; + } + + @JsonAttribute(name = "bid_size") + public void setBidSize(Double bidSize) { + this.bidSize = bidSize; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Reconnect.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Reconnect.java new file mode 100644 index 0000000000..6abb0298f5 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Reconnect.java @@ -0,0 +1,23 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; + +@CompiledJson +public class Reconnect extends MessageBase { + + private Integer withinSeconds; + private OffsetDateTime beforeTime; + + public Integer getWithinSeconds() { return withinSeconds; } + + @JsonAttribute(name = "within_seconds") + public void setWithinSeconds(Integer withinSeconds) { this.withinSeconds = withinSeconds; } + + public OffsetDateTime getBeforeTime() { return beforeTime; } + + @JsonAttribute(name = "before_time") + public void setBeforeTime(OffsetDateTime beforeTime) { this.beforeTime = beforeTime; } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Trades.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Trades.java new file mode 100644 index 0000000000..7ff6d8eb94 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Trades.java @@ -0,0 +1,87 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; + +@CompiledJson +public class Trades extends MessageBase { + + private String symbolId; + private Integer sequence; + private OffsetDateTime timeExchange; + private OffsetDateTime timeCoinApi; + private String uuid; + private Double price; + private Double size; + private String takerSide; + + public String getSymbolId() { + return symbolId; + } + + @JsonAttribute(name = "symbol_id") + public void setSymbolId(String symbolId) { + this.symbolId = symbolId; + } + + public Integer getSequence() { + return sequence; + } + + public void setSequence(Integer sequence) { + this.sequence = sequence; + } + + public OffsetDateTime getTimeExchange() { + return timeExchange; + } + + @JsonAttribute(name = "time_exchange") + public void setTimeExchange(OffsetDateTime timeExchange) { + this.timeExchange = timeExchange; + } + + public OffsetDateTime getTimeCoinApi() { + return timeCoinApi; + } + + @JsonAttribute(name = "time_coinapi") + public void setTimeCoinApi(OffsetDateTime timeCoinApi) { + this.timeCoinApi = timeCoinApi; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + + public Double getSize() { + return size; + } + + public void setSize(Double size) { + this.size = size; + } + + public String getTakerSide() { + return takerSide; + } + + @JsonAttribute(name = "taker_side") + public void setTakerSide(String takerSide) { + this.takerSide = takerSide; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Volume.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Volume.java new file mode 100644 index 0000000000..06e78eef22 --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/Volume.java @@ -0,0 +1,42 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +import java.time.OffsetDateTime; +import java.util.List; + +@CompiledJson +public class Volume extends MessageBase { + + private String periodId; + private OffsetDateTime timeCoinApi; + private List volumeBySymbol; + + public String getPeriodId() { + return periodId; + } + + @JsonAttribute(name = "period_id") + public void setPeriodId(String periodId) { + this.periodId = periodId; + } + + public OffsetDateTime getTimeCoinApi() { + return timeCoinApi; + } + + @JsonAttribute(name = "time_coinapi") + public void setTimeCoinApi(OffsetDateTime timeCoinApi) { + this.timeCoinApi = timeCoinApi; + } + + public List getVolumeBySymbol() { + return volumeBySymbol; + } + + @JsonAttribute(name = "volume_by_symbol") + public void setVolumeBySymbol(List volumeBySymbol) { + this.volumeBySymbol = volumeBySymbol; + } +} diff --git a/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/VolumeBySymbol.java b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/VolumeBySymbol.java new file mode 100644 index 0000000000..f6efa8d87f --- /dev/null +++ b/data-api/java-websocket/src/main/java/io/coinapi/websocket/model/VolumeBySymbol.java @@ -0,0 +1,59 @@ +package io.coinapi.websocket.model; + +import com.dslplatform.json.CompiledJson; +import com.dslplatform.json.JsonAttribute; + +@CompiledJson +public class VolumeBySymbol { + + private String symbolId; + private String assetIdBase; + private String assetIdQuote; + private Double volumeBase; + private Double volumeQuote; + + public String getSymbolId() { + return symbolId; + } + + @JsonAttribute(name = "symbol_id") + public void setSymbolId(String symbolId) { + this.symbolId = symbolId; + } + + public String getAssetIdBase() { + return assetIdBase; + } + + @JsonAttribute(name = "asset_id_base") + public void setAssetIdBase(String assetIdBase) { + this.assetIdBase = assetIdBase; + } + + public String getAssetIdQuote() { + return assetIdQuote; + } + + @JsonAttribute(name = "asset_id_quote") + public void setAssetIdQuote(String assetIdQuote) { + this.assetIdQuote = assetIdQuote; + } + + public Double getVolumeBase() { + return volumeBase; + } + + @JsonAttribute(name = "volume_base") + public void setVolumeBase(Double volumeBase) { + this.volumeBase = volumeBase; + } + + public Double getVolumeQuote() { + return volumeQuote; + } + + @JsonAttribute(name = "volume_quote") + public void setVolumeQuote(Double volumeQuote) { + this.volumeQuote = volumeQuote; + } +} diff --git a/data-api/java-websocket/src/main/resources/config.properties b/data-api/java-websocket/src/main/resources/config.properties new file mode 100644 index 0000000000..a0682c01b2 --- /dev/null +++ b/data-api/java-websocket/src/main/resources/config.properties @@ -0,0 +1 @@ +coinapi_key=YOUR_API_KEY_HERE \ No newline at end of file diff --git a/data-api/java-websocket/src/test/java/BookTest.java b/data-api/java-websocket/src/test/java/BookTest.java new file mode 100644 index 0000000000..497b669ad2 --- /dev/null +++ b/data-api/java-websocket/src/test/java/BookTest.java @@ -0,0 +1,76 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class BookTest extends CoinAPISDKTest{ + + @Test + public void getBookMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setBookInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("book")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } + + @Test + public void getBook5Messages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setBookInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("book5")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } + + @Test + public void getBook20Messages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setBookInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("book20")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } + + @Test + public void getBook50Messages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setBookInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("book50")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/CoinAPISDKTest.java b/data-api/java-websocket/src/test/java/CoinAPISDKTest.java new file mode 100644 index 0000000000..f456f7230a --- /dev/null +++ b/data-api/java-websocket/src/test/java/CoinAPISDKTest.java @@ -0,0 +1,26 @@ +import io.coinapi.websocket.CoinAPIWebSocket; +import io.coinapi.websocket.CoinAPIWebSocketImpl; +import io.coinapi.websocket.model.Hello; +import org.junit.Before; + +import java.io.IOException; + +public abstract class CoinAPISDKTest { + + protected String apikey; + protected CoinAPIWebSocket coinAPIWebSocket; + + @Before + public void configuration() throws IOException { + Config config = new Config(); + apikey = config.getPropValues("coinapi_key"); + coinAPIWebSocket = new CoinAPIWebSocketImpl(true); + } + + public Hello createHello(String type) { + Hello hello = new Hello(); + hello.setApikey(apikey); + hello.setSubscribeDataType(new String[]{type}); + return hello; + } +} diff --git a/data-api/java-websocket/src/test/java/Config.java b/data-api/java-websocket/src/test/java/Config.java new file mode 100644 index 0000000000..39034738f0 --- /dev/null +++ b/data-api/java-websocket/src/test/java/Config.java @@ -0,0 +1,32 @@ +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class Config { + + private InputStream inputStream; + + public String getPropValues(String name) throws IOException { + + try { + Properties properties = new Properties(); + String fileName = "config.properties"; + + inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream != null) { + properties.load(inputStream); + } else { + throw new FileNotFoundException("property file " + fileName + " not found in the classpath"); + } + return properties.getProperty(name); + } + catch (Exception e) { + System.out.println(e); + } + finally { + inputStream.close(); + } + return null; + } +} diff --git a/data-api/java-websocket/src/test/java/ErrorTest.java b/data-api/java-websocket/src/test/java/ErrorTest.java new file mode 100644 index 0000000000..d7453ecc7b --- /dev/null +++ b/data-api/java-websocket/src/test/java/ErrorTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class ErrorTest extends CoinAPISDKTest { + + @Test + public void getErrorMessage() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setErrorInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("invalid_type")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " error message"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/MessageInjectableCoinAPISDKTest.java b/data-api/java-websocket/src/test/java/MessageInjectableCoinAPISDKTest.java new file mode 100644 index 0000000000..8a028eb31a --- /dev/null +++ b/data-api/java-websocket/src/test/java/MessageInjectableCoinAPISDKTest.java @@ -0,0 +1,39 @@ +import io.coinapi.websocket.CoinAPIWebSocketImpl; +import io.coinapi.websocket.model.Hello; +import org.junit.Before; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.Queue; +import java.util.concurrent.LinkedBlockingDeque; + +public abstract class MessageInjectableCoinAPISDKTest { + protected String apikey; + protected CoinAPIWebSocketImpl coinAPIWebSocket; + protected Queue messagesQueue; + + @Before + public void configuration() throws IOException, NoSuchFieldException, IllegalAccessException { + Config config = new Config(); + apikey = config.getPropValues("coinapi_key"); + + //make private messagesQueue variable accessible for injecting messages during testing + Field messagesQueueField = CoinAPIWebSocketImpl.class.getDeclaredField("messagesQueue"); + messagesQueueField.setAccessible(true); + + coinAPIWebSocket = new CoinAPIWebSocketImpl(true); + + //inject this public queue into the class + Queue messagesQueueToSet = new LinkedBlockingDeque(); + messagesQueueField.set(coinAPIWebSocket, messagesQueueToSet); + + messagesQueue = messagesQueueToSet; + } + + public Hello createHello(String type) { + Hello hello = new Hello(); + hello.setApikey(apikey); + hello.setSubscribeDataType(new String[]{type}); + return hello; + } +} diff --git a/data-api/java-websocket/src/test/java/OHLCVTest.java b/data-api/java-websocket/src/test/java/OHLCVTest.java new file mode 100644 index 0000000000..71d247dd5a --- /dev/null +++ b/data-api/java-websocket/src/test/java/OHLCVTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class OHLCVTest extends CoinAPISDKTest { + + @Test + public void getOHLCVMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setOHLCVInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("ohlcv")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " ohlcv messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/QuotesTest.java b/data-api/java-websocket/src/test/java/QuotesTest.java new file mode 100644 index 0000000000..cd489bc093 --- /dev/null +++ b/data-api/java-websocket/src/test/java/QuotesTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class QuotesTest extends CoinAPISDKTest { + + @Test + public void getQuoteMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setQuotesInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("quote")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " quote messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/ReconnectTest.java b/data-api/java-websocket/src/test/java/ReconnectTest.java new file mode 100644 index 0000000000..121252b308 --- /dev/null +++ b/data-api/java-websocket/src/test/java/ReconnectTest.java @@ -0,0 +1,39 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class ReconnectTest extends MessageInjectableCoinAPISDKTest { + + @Test + public void getReconnectMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setOHLCVInvoke(message -> { + //stub invoke to allow connection + }); + + coinAPIWebSocket.setReconnectInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + + coinAPIWebSocket.sendHelloMessage(createHello("ohlcv")); + + String message = "{" + + "\"type\": \"reconnect\"," + + "\"within_seconds\": 10," + + "\"before_time\": \"2020-08-06T19:19:09.7035429Z\"" + + "}"; + + //inject reconnect message into exposed queue + messagesQueue.add(message); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " reconnect messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertEquals(1, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/TradesTest.java b/data-api/java-websocket/src/test/java/TradesTest.java new file mode 100644 index 0000000000..75142c55e9 --- /dev/null +++ b/data-api/java-websocket/src/test/java/TradesTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class TradesTest extends CoinAPISDKTest { + + @Test + public void getTradeMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setTradesInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("trade")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " trade messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/data-api/java-websocket/src/test/java/VolumeTest.java b/data-api/java-websocket/src/test/java/VolumeTest.java new file mode 100644 index 0000000000..28f0ae116e --- /dev/null +++ b/data-api/java-websocket/src/test/java/VolumeTest.java @@ -0,0 +1,25 @@ +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; + +public class VolumeTest extends CoinAPISDKTest { + + @Test + public void getVolumeMessages() throws IOException, InterruptedException { + + AtomicReference msgCount = new AtomicReference<>(0); + + coinAPIWebSocket.setVolumeInvoke(message -> { + msgCount.getAndSet(msgCount.get() + 1); + }); + coinAPIWebSocket.sendHelloMessage(createHello("volume")); + + Thread.sleep(10000); + System.out.println("processing " + msgCount.get() + " volume messages"); + + coinAPIWebSocket.closeConnect(); + Assert.assertNotEquals(0, msgCount.get().intValue()); + } +} diff --git a/javascript-rest/coinapi_v1.js b/data-api/javascript-rest/coinapi_v1.js similarity index 88% rename from javascript-rest/coinapi_v1.js rename to data-api/javascript-rest/coinapi_v1.js index 7ad6a99fd2..ba3b348e26 100644 --- a/javascript-rest/coinapi_v1.js +++ b/data-api/javascript-rest/coinapi_v1.js @@ -6,9 +6,6 @@ if (typeof window !== 'undefined') { } var axios = typeof window === 'undefined' ? require("axios") : window.axios; var ISO_8601 = /^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,9})?(?:Z|[+-][01]\d:[0-5]\d)$/; -function formatDate(d) { - return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear(); -} var transformResponse = axios.defaults.transformResponse.concat(function (data) { var tmp = function (item) { return Object.keys(item).forEach(function (k) { // console.log(item[k], ISO_8601.test(item[k])) @@ -104,7 +101,7 @@ var COIN_API_SDK = (function () { var path = this.url + ("/v1/ohlcv/" + symbol_id + "/history?period_id=" + period_id + "&time_start=" + time_start.toISOString()); var params = {}; if (time_end) { - params.time = time_end.toISOString(); + params.time_end = time_end.toISOString(); } if (limit) { params.limit = limit; @@ -144,7 +141,7 @@ var COIN_API_SDK = (function () { var path = this.url + ("/v1/trades/" + symbol_id + "/history?time_start=" + time_start.toISOString()); var params = {}; if (time_end) { - params.time = time_end.toISOString(); + params.time_end = time_end.toISOString(); } if (limit) { params.limit = limit; @@ -198,7 +195,7 @@ var COIN_API_SDK = (function () { var path = this.url + ("/v1/quotes/" + symbol_id + "/history?time_start=" + time_start.toISOString()); var params = {}; if (time_end) { - params.time = time_end.toISOString(); + params.time_end = time_end.toISOString(); } if (limit) { params.limit = limit; @@ -208,9 +205,13 @@ var COIN_API_SDK = (function () { return resp.data; }); }; - COIN_API_SDK.prototype.orderbooks_current_data_all = function () { + COIN_API_SDK.prototype.orderbooks_current_data_all = function (filter_symbol_id) { + if (filter_symbol_id === void 0) { filter_symbol_id = null; } var path = this.url + "/v1/orderbooks/current"; var params = {}; + if (filter_symbol_id) { + params.filter_symbol_id = filter_symbol_id; + } return axios.get(path, { headers: this.headers, transformResponse: transformResponse, params: params }) .then(function (resp) { return resp.data; @@ -241,35 +242,7 @@ var COIN_API_SDK = (function () { var path = this.url + ("/v1/orderbooks/" + symbol_id + "/history?time_start=" + time_start.toISOString()); var params = {}; if (time_end) { - params.time = time_end.toISOString(); - } - if (limit) { - params.limit = limit; - } - return axios.get(path, { headers: this.headers, transformResponse: transformResponse, params: params }) - .then(function (resp) { - return resp.data; - }); - }; - COIN_API_SDK.prototype.twitter_latest_data = function (limit) { - if (limit === void 0) { limit = null; } - var path = this.url + "/v1/twitter/latest"; - var params = {}; - if (limit) { - params.limit = limit; - } - return axios.get(path, { headers: this.headers, transformResponse: transformResponse, params: params }) - .then(function (resp) { - return resp.data; - }); - }; - COIN_API_SDK.prototype.twitter_historical_data = function (time_start, time_end, limit) { - if (time_end === void 0) { time_end = null; } - if (limit === void 0) { limit = null; } - var path = this.url + ("/v1/twitter/history?time_start=" + time_start.toISOString()); - var params = {}; - if (time_end) { - params.time = time_end.toISOString(); + params.time_end = time_end.toISOString(); } if (limit) { params.limit = limit; diff --git a/data-api/javascript-rest/example_javascript.html b/data-api/javascript-rest/example_javascript.html new file mode 100644 index 0000000000..72390ead83 --- /dev/null +++ b/data-api/javascript-rest/example_javascript.html @@ -0,0 +1,9 @@ + +
This is title
+ +Open dev console to see example output + + + + + \ No newline at end of file diff --git a/javascript-rest/example_javascript.js b/data-api/javascript-rest/example_javascript.js similarity index 91% rename from javascript-rest/example_javascript.js rename to data-api/javascript-rest/example_javascript.js index cb79a2350a..21c310e35c 100644 --- a/javascript-rest/example_javascript.js +++ b/data-api/javascript-rest/example_javascript.js @@ -120,17 +120,6 @@ function run() { Orderbooks_historical_data.forEach(x=> { console.log(x) }) }); - sdk.twitter_latest_data(5).then(function (Twitter_latest_data) { - console.log('Twitter_latest_data:') - console.log('number: ', Twitter_latest_data.length) - Twitter_latest_data.forEach(x=> { console.log(x) }) - - }); - sdk.twitter_historical_data(t, new Date(), 5).then(function (Twitter_historical_data) { - console.log('Twitter_historical_data:') - console.log('number: ', Twitter_historical_data.length) - Twitter_historical_data.forEach(x=> { console.log(x) }) - }) } run(); \ No newline at end of file diff --git a/data-api/javascript-rest/example_typescript.html b/data-api/javascript-rest/example_typescript.html new file mode 100644 index 0000000000..65b0966d17 --- /dev/null +++ b/data-api/javascript-rest/example_typescript.html @@ -0,0 +1,9 @@ + +
This is title
+ +Open dev console to see example output + + + + + \ No newline at end of file diff --git a/javascript-rest/example_typescript.js b/data-api/javascript-rest/example_typescript.js similarity index 93% rename from javascript-rest/example_typescript.js rename to data-api/javascript-rest/example_typescript.js index ca39fc3f3a..50033b997c 100644 --- a/javascript-rest/example_typescript.js +++ b/data-api/javascript-rest/example_typescript.js @@ -40,7 +40,7 @@ var COIN_API_SDK = typeof window !== 'undefined' ? window.COIN_API_SDK : coinapi var sdk = new COIN_API_SDK("YOUR_API_KEY_HERE"); function run() { return __awaiter(this, void 0, void 0, function () { - var t, exchanges, Metadata_list_assets, Metadata_list_symbols, Exchange_rates_get_specific_rate, Exchange_rates_get_all_current_rates, Ohlcv_list_all_periods, Ohlcv_latest_data, Ohlcv_historic_data, Trades_latest_data_all, Trades_latest_data_symbol, Trades_historical_data, Quotes_current_data_all, Quotes_current_data_symbol, Quotes_latest_data_all, Quotes_latest_data_symbol, Quotes_historical_data, Orderbooks_current_data_all, Orderbooks_current_data_symbol, Orderbooks_latest_data, Orderbooks_historical_data, Twitter_latest_data, Twitter_historical_data; + var t, exchanges, Metadata_list_assets, Metadata_list_symbols, Exchange_rates_get_specific_rate, Exchange_rates_get_all_current_rates, Ohlcv_list_all_periods, Ohlcv_latest_data, Ohlcv_historic_data, Trades_latest_data_all, Trades_latest_data_symbol, Trades_historical_data, Quotes_current_data_all, Quotes_current_data_symbol, Quotes_latest_data_all, Quotes_latest_data_symbol, Quotes_historical_data, Orderbooks_current_data_all, Orderbooks_current_data_symbol, Orderbooks_latest_data, Orderbooks_historical_data; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -161,18 +161,6 @@ function run() { console.log('Orderbooks_historical_data:'); console.log('number: ', Orderbooks_historical_data.length); Orderbooks_historical_data.forEach(function (x) { console.log(x); }); - return [4 /*yield*/, sdk.twitter_latest_data(5)]; - case 21: - Twitter_latest_data = _a.sent(); - console.log('Twitter_latest_data:'); - console.log('number: ', Twitter_latest_data.length); - Twitter_latest_data.forEach(function (x) { console.log(x); }); - return [4 /*yield*/, sdk.twitter_historical_data(t, new Date(), 5)]; - case 22: - Twitter_historical_data = _a.sent(); - console.log('Twitter_historical_data:'); - console.log('number: ', Twitter_historical_data.length); - Twitter_historical_data.forEach(function (x) { console.log(x); }); return [2 /*return*/]; } }); diff --git a/data-api/javascript-rest/package.json b/data-api/javascript-rest/package.json new file mode 100644 index 0000000000..06cc18eeae --- /dev/null +++ b/data-api/javascript-rest/package.json @@ -0,0 +1,16 @@ +{ + "name": "typescript-rest", + "version": "1.0.0", + "description": "coinapi.io typescript sdk", + "main": "coinapi_v1.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "imRaziel", + "license": "MIT", + "dependencies": { + "@types/es6-promise": "0.0.32", + "axios": "^0.19.2" + }, + "repository": "https://github.com/coinapi/coinapi-sdk/tree/master/javascript-rest" +} diff --git a/javascript-rest/readme.md b/data-api/javascript-rest/readme.md similarity index 100% rename from javascript-rest/readme.md rename to data-api/javascript-rest/readme.md diff --git a/data-api/matlab/README.md b/data-api/matlab/README.md new file mode 100644 index 0000000000..95301202e2 --- /dev/null +++ b/data-api/matlab/README.md @@ -0,0 +1 @@ +https://support.coinapi.io/hc/en-us/articles/360026657331-How-to-use-CoinAPI-from-Matlab- diff --git a/data-api/nodejs-ws/example.js b/data-api/nodejs-ws/example.js new file mode 100644 index 0000000000..8da4818905 --- /dev/null +++ b/data-api/nodejs-ws/example.js @@ -0,0 +1,17 @@ +const WebSocket = require('ws'); + +var ws = new WebSocket('wss://ws.coinapi.io/v1/'); +ws.on('open', function open() { +var hello = { + "type": "hello", + "apikey": "PUT_API_KEY_HERE", + "heartbeat": false, + "subscribe_data_type": ["quote"], + "subscribe_filter_asset_id": ["BTC", "ETH"] +}; +ws.send(JSON.stringify(hello)); +}); + +ws.on('message', function incoming(data) { + console.log(data); +}); \ No newline at end of file diff --git a/data-api/nodejs-ws/readme.md b/data-api/nodejs-ws/readme.md new file mode 100644 index 0000000000..23de4c3f76 --- /dev/null +++ b/data-api/nodejs-ws/readme.md @@ -0,0 +1,7 @@ +To run javascript example: + +``` +cd /path/to/sdk/folder +npm install --save ws +node ./example.js +``` diff --git a/objc-rest/CoinAPI.h b/data-api/objc-rest/CoinAPI.h similarity index 91% rename from objc-rest/CoinAPI.h rename to data-api/objc-rest/CoinAPI.h index a4e0f1c999..0c99bfc974 100644 --- a/objc-rest/CoinAPI.h +++ b/data-api/objc-rest/CoinAPI.h @@ -45,10 +45,6 @@ - (void)getLatestOrderbooksData:(NSString*)symbol_id limit:(NSInteger)limit; - (void)getHistoricalOrderbooksData:(NSString*)symbol_id time_start:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit; -/** Twitter Functions **/ -- (void)getLatestTwitterData:(NSInteger)limit; -- (void)getHistoricalTwitterData:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit; - /*************** Websocket API ***************/ @end diff --git a/data-api/objc-rest/CoinAPI.m b/data-api/objc-rest/CoinAPI.m new file mode 100644 index 0000000000..5deb8a5974 --- /dev/null +++ b/data-api/objc-rest/CoinAPI.m @@ -0,0 +1,325 @@ +// +// RestCoinAPI.m +// RestCoinAPI +// +// Created by MyMac on 26/05/2017. +// Copyright © 2017 Panda Mobile. All rights reserved. +// + +#define COINAPI_URL @"https://rest.coinapi.io/" + +#import "CoinAPI.h" + +@implementation CoinAPI + +- (id)init +{ + self = [super init]; + if (self) { + strAPIKey = @""; + } + return self; +} + +- (id)initWithAPIKey:(NSString*)strAPI +{ + self = [super init]; + if (self) { + // All initializations, for example: + strAPIKey = strAPI; + } + return self; +} + +/** Metadata Functions **/ +- (void)getAllMetadataExchanges +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/exchanges"]; + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Metadata - List all exchanges : %@", jsonResult); + }] resume]; +} + +- (void)getAllMetadataAssets +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/assets"]; + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Metadata - List all assets : %@", jsonResult); + }] resume]; +} +- (void)getAllMetadataSymbols +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/symbols"]; + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Metadata - List all symbols : %@", jsonResult); + }] resume]; +} + +/** Exchange Rates Functions **/ +- (void)getSpecificExchangeRates:(NSString*)asset_id_base asset_id_quote:(NSString*)asset_id_quote time:(NSInteger)time +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/exchangerate/%@/%@", asset_id_base, asset_id_quote]]; + if (time > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/exchangerate/%@/%@?time=%ld", asset_id_base, asset_id_quote, time]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Exchange Rates - Get specific rate : %@", jsonResult); + }] resume]; +} +- (void)getAllExchangeRates:(NSString*)asset_id_base +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/exchangerate/%@", asset_id_base]]; + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Exchange Rates - Get all current rates : %@", jsonResult); + }] resume]; +} + +/** OHLCV Functions **/ +- (void)getAllOHLCVPeriods +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/ohlcv/periods"]; + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"OHLCV - List all periods : %@", jsonResult); + }] resume]; +} +- (void)getLatestOHLCVData:(NSString*)symbol_id period_id:(NSString*)period_id limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/ohlcv/%@/latest?period_id=%@", symbol_id, period_id]]; + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/ohlcv/%@/latest?period_id=%@&limit=%ld", symbol_id, period_id, limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"OHLCV - Latest data : %@", jsonResult); + }] resume]; +} +- (void)getHistoricalOHLCVData:(NSString*)symbol_id period_id:(NSString*)period_id time_start:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/ohlcv/%@/latest?period_id=%@&time_start=%@", symbol_id, period_id, time_start]]; + if (time_end){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&time_end=%@", [url absoluteString], time_end]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&limit=%ld", [url absoluteString], limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"OHLCV - Historical data : %@", jsonResult); + }] resume]; +} + +/** Trades Functions **/ +- (void)getLatestTradesData:(NSString*)symbol_id limit:(NSInteger)limit; +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/trades/latest"]; + if (symbol_id){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/trades/%@/latest", symbol_id]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?limit=%ld", [url absoluteString], limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Trades - Latest data : %@", jsonResult); + }] resume]; +} + +- (void)getHistoricalTradesData:(NSString*)symbol_id time_start:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/trades/%@/history?time_start=%@", symbol_id, time_start]]; + if (time_end){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&time_end=%@", [url absoluteString], time_end]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&limit=%ld", [url absoluteString], limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Trades - Historical data : %@", jsonResult); + }] resume]; +} + +/** Quotes Functions **/ +- (void)getCurrentQuotesData:(NSString*)symbol_id +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/quotes/current"]; + if (symbol_id){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/quotes/%@/current", symbol_id]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Quotes - Current data : %@", jsonResult); + }] resume]; +} + +- (void)getLatestQuotesData:(NSString*)symbol_id limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/quotes/latest"]; + if (symbol_id){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/quotes/%@/latest", symbol_id]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&limit=%ld", [url absoluteString], limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Quotes - Latest data : %@", jsonResult); + }] resume]; +} + +- (void)getHistoricalQuotesData:(NSString*)symbol_id time_start:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/quotes/%@/history?time_start=%@", symbol_id, time_start]]; + if (time_end){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&time_end=%@", [url absoluteString], time_end]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&limit=%ld", [url absoluteString], limit]]; + } + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Quotes - Historical data : %@", jsonResult); + }] resume]; +} + +/** Orderbooks Functions **/ +- (void)getCurrentOrderbooksData:(NSString*)symbol_id +{ + NSURL *url = [NSURL URLWithString:@"https://rest.coinapi.io/v1/orderbooks/current"]; + if (symbol_id){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/orderbooks/%@/current", symbol_id]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Orderbooks - Current data : %@", jsonResult); + }] resume]; +} + +- (void)getLatestOrderbooksData:(NSString*)symbol_id limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/orderbooks/%@/latest", symbol_id]]; + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?limit=%ld", [url absoluteString], limit]]; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Orderbooks - Latest data : %@", jsonResult); + }] resume]; +} + +- (void)getHistoricalOrderbooksData:(NSString*)symbol_id time_start:(NSString*)time_start time_end:(NSString*)time_end limit:(NSInteger)limit +{ + NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://rest.coinapi.io/v1/orderbooks/%@/history?time_start=%@", symbol_id, time_start]]; + if (time_end){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&time_end=%@", [url absoluteString], time_end]]; + } + if (limit > 0){ + url = [NSURL URLWithString:[NSString stringWithFormat:@"%@&limit=%ld", [url absoluteString], limit]]; + } + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100]; + [request setHTTPMethod: @"GET"]; + [request addValue:strAPIKey forHTTPHeaderField:@"X-CoinAPI-Key"] ; + + NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + NSLog(@"Orderbooks - Historical data : %@", jsonResult); + }] resume]; +} + +@end diff --git a/objc-rest/ViewController.h b/data-api/objc-rest/ViewController.h similarity index 100% rename from objc-rest/ViewController.h rename to data-api/objc-rest/ViewController.h diff --git a/objc-rest/ViewController.m b/data-api/objc-rest/ViewController.m similarity index 93% rename from objc-rest/ViewController.m rename to data-api/objc-rest/ViewController.m index fcb79cdb4c..5687ac350f 100644 --- a/objc-rest/ViewController.m +++ b/data-api/objc-rest/ViewController.m @@ -60,9 +60,6 @@ - (void)viewWillAppear:(BOOL)animated [coin getLatestOrderbooksData:@"BITSTAMP_SPOT_BTC_USD" limit:0]; [coin getHistoricalOrderbooksData:@"BITSTAMP_SPOT_BTC_USD" time_start:@"2016-01-01T00:00:00" time_end:NULL limit:0]; - /* Twitter Functions */ - [coin getLatestTwitterData:0]; - [coin getHistoricalTwitterData:@"2016-01-01T00:00:00" time_end:NULL limit:0]; } diff --git a/php-rest/README.md b/data-api/php-rest/README.md similarity index 100% rename from php-rest/README.md rename to data-api/php-rest/README.md diff --git a/php-rest/coinapi.inc.php b/data-api/php-rest/coinapi.inc.php similarity index 89% rename from php-rest/coinapi.inc.php rename to data-api/php-rest/coinapi.inc.php index a1ca28d78f..5beccc983f 100644 --- a/php-rest/coinapi.inc.php +++ b/data-api/php-rest/coinapi.inc.php @@ -297,46 +297,6 @@ function GetOrderbookHistory($symbol_id, $time_start, $time_end = null, $limit = } return $this->CurlRequest($url); } - //Twitter - function GetTwitterLatest($limit = null) - { - if ($limit == null) - { - $url = 'https://rest.coinapi.io/v1/twitter/latest'; - } - else - { - $url = 'https://rest.coinapi.io/v1/twitter/latest?limit=' . $limit; - } - return $this->CurlRequest($url); - } - function GetTwitterHistory($time_start, $time_end = null, $limit = null) - { - if ($time_start == null) - { - throw new InvalidArgumentException("time_start is required"); - } - $time_start = $this->FormatDateTime($time_start); - if ($time_end == null && $limit != null) - { - $url = 'https://rest.coinapi.io/v1/twitter/history?time_start=' . $time_start . '&limit=' . $limit; - } - else if ($limit == null && $time_end != null) - { - $time_end = $this->FormatDateTime($time_end); - $url = 'https://rest.coinapi.io/v1/twitter/history?time_start=' . $time_start . '&time_end=' . $time_end; - } - else if ($limit == null && $time_end == null) - { - $url = 'https://rest.coinapi.io/v1/twitter/history?time_start=' . $time_start; - } - else - { - $time_end = $this->FormatDateTime($time_end); - $url = 'https://rest.coinapi.io/v1/twitter/history?time_start=' . $time_start . '&time_end=' . $time_end . '&limit=' . $limit; - } - return $this->CurlRequest($url); - } //Formate DateTime Object function FormatDateTime($DateTimeObj) { diff --git a/php-rest/example.php b/data-api/php-rest/example.php similarity index 92% rename from php-rest/example.php rename to data-api/php-rest/example.php index 6a3dd923c0..a8092c3ed5 100644 --- a/php-rest/example.php +++ b/data-api/php-rest/example.php @@ -53,8 +53,4 @@ print_r($capi->GetOrderbookLatest($symbol_id, $limit)); // get history Orderbooks from specific symbol and time range print_r($capi->GetOrderbookHistory($symbol_id, $time_start, $time_end, $limit)); -// get latest twitter data -print_r($capi->GetTwitterLatest($limit)); -// get history twitter data from specific time range -print_r($capi->GetTwitterHistory($time_start, $time_end, $limit)); ?> diff --git a/data-api/python-rest/LICENSE b/data-api/python-rest/LICENSE new file mode 100644 index 0000000000..335ea9d070 --- /dev/null +++ b/data-api/python-rest/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018 The Python Packaging Authority + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/data-api/python-rest/README.md b/data-api/python-rest/README.md new file mode 100644 index 0000000000..891f7bd4b7 --- /dev/null +++ b/data-api/python-rest/README.md @@ -0,0 +1,23 @@ +**Requirements:** + * Python >= 3 + +**Install using:** + +```bash +pip install --upgrade coinapi_rest_v1 +``` + +**Import this way** + +```python +from coinapi_rest_v1.restapi import CoinAPIv1 +``` + +**To run examples:** + +```bash +git clone https://github.com/coinapi/coinapi-sdk/ +cd coinapi-sdk/data-api/python-rest/coinapi_rest_v1 +# edit examples.py, fill your API key inside of it +python examples.py YOUR_API_KEY +``` diff --git a/data-api/python-rest/coinapi_rest_v1/__init__.py b/data-api/python-rest/coinapi_rest_v1/__init__.py new file mode 100644 index 0000000000..5a95e4c531 --- /dev/null +++ b/data-api/python-rest/coinapi_rest_v1/__init__.py @@ -0,0 +1,7 @@ +name = "coinapi.rest.v1" + +from . import restapi + +__all__ = [ + 'restapi' +] \ No newline at end of file diff --git a/data-api/python-rest/coinapi_rest_v1/examples.py b/data-api/python-rest/coinapi_rest_v1/examples.py new file mode 100644 index 0000000000..ad77587a5b --- /dev/null +++ b/data-api/python-rest/coinapi_rest_v1/examples.py @@ -0,0 +1,266 @@ +from coinapi_rest_v1.restapi import CoinAPIv1 +import datetime, sys + +test_key = sys.argv[1] + +api = CoinAPIv1(test_key) +exchanges = api.metadata_list_exchanges() + +print('Exchanges') +for exchange in exchanges: + print('Exchange ID: %s' % exchange['exchange_id']) + print('Exchange website: %s' % exchange['website']) + print('Exchange name: %s' % exchange['name']) + +assets = api.metadata_list_assets() +print('Assets') +for asset in assets: + print('Asset ID: %s' % asset['asset_id']) + try: + print('Asset name: %s' % asset['name']) + except KeyError: + print('Can not find name') + print('Asset type (crypto?): %s' % asset['type_is_crypto']) + +symbols = api.metadata_list_symbols() +print('Symbols') +for symbol in symbols: + print('Symbol ID: %s' % symbol['symbol_id']) + print('Exchange ID: %s' % symbol['exchange_id']) + print('Symbol type: %s' % symbol['symbol_type']) + try: + print('Asset ID base: %s' % symbol['asset_id_base']) + except KeyError: + print('Can not find Asset ID base') + try: + print('Asset ID quote: %s' % symbol['asset_id_quote']) + except KeyError: + print('Can not find Asset ID quote') + + if (symbol['symbol_type'] == 'FUTURES'): + print('Future delivery time: %s' % symbol['future_delivery_time']) + + if (symbol['symbol_type'] == 'OPTION'): + print('Option type is call: %s' % symbol['option_type_is_call']) + print('Option strike price: %s' % symbol['option_strike_price']) + print('Option contract unit: %s' % symbol['option_contract_unit']) + print('Option exercise style: %s' % symbol['option_exercise_style']) + print('Option expiration time: %s' % symbol['option_expiration_time']) + +exchange_rate = api.exchange_rates_get_specific_rate('BTC', 'USD') +print('Time: %s' % exchange_rate['time']) +print('Base: %s' % exchange_rate['asset_id_base']) +print('Quote: %s' % exchange_rate['asset_id_quote']) +print('Rate: %s' % exchange_rate['rate']) +last_week = datetime.date(2017, 5, 16).isoformat() + +exchange_rate_last_week = api.exchange_rates_get_specific_rate('BTC', 'USD', {'time': last_week}) +print('Time: %s' % exchange_rate_last_week['time']) +print('Base: %s' % exchange_rate_last_week['asset_id_base']) +print('Quote: %s' % exchange_rate_last_week['asset_id_quote']) +print('Rate: %s' % exchange_rate_last_week['rate']) + +current_rates = api.exchange_rates_get_all_current_rates('BTC') + +print("Asset ID Base: %s" % current_rates['asset_id_base']) +for rate in current_rates['rates']: + print('Time: %s' % rate['time']) + print('Quote: %s' % rate['asset_id_quote']) + print('Rate: %s' % rate['rate']) + +periods = api.ohlcv_list_all_periods() + +for period in periods: + print('ID: %s' % period['period_id']) + print('Seconds: %s' % period['length_seconds']) + print('Months: %s' % period['length_months']) + print('Unit count: %s' % period['unit_count']) + print('Unit name: %s' % period['unit_name']) + print('Display name: %s' % period['display_name']) + +ohlcv_latest = api.ohlcv_latest_data('BITSTAMP_SPOT_BTC_USD', {'period_id': '1MIN'}) + +for period in ohlcv_latest: + print('Period start: %s' % period['time_period_start']) + print('Period end: %s' % period['time_period_end']) + print('Time open: %s' % period['time_open']) + print('Time close: %s' % period['time_close']) + print('Price open: %s' % period['price_open']) + print('Price close: %s' % period['price_close']) + print('Price low: %s' % period['price_low']) + print('Price high: %s' % period['price_high']) + print('Volume traded: %s' % period['volume_traded']) + print('Trades count: %s' % period['trades_count']) + +start_of_2016 = datetime.date(2016, 1, 1).isoformat() +ohlcv_historical = api.ohlcv_historical_data('BITSTAMP_SPOT_BTC_USD', {'period_id': '1MIN', 'time_start': start_of_2016}) + +for period in ohlcv_historical: + print('Period start: %s' % period['time_period_start']) + print('Period end: %s' % period['time_period_end']) + print('Time open: %s' % period['time_open']) + print('Time close: %s' % period['time_close']) + print('Price open: %s' % period['price_open']) + print('Price close: %s' % period['price_close']) + print('Price low: %s' % period['price_low']) + print('Price high: %s' % period['price_high']) + print('Volume traded: %s' % period['volume_traded']) + print('Trades count: %s' % period['trades_count']) + +latest_trades = api.trades_latest_data_all() + +for data in latest_trades: + print('Symbol ID: %s' % data['symbol_id']) + print('Time Exchange: %s' % data['time_exchange']) + print('Time CoinAPI: %s' % data['time_coinapi']) + print('UUID: %s' % data['uuid']) + print('Price: %s' % data['price']) + print('Size: %s' % data['size']) + print('Taker Side: %s' % data['taker_side']) + +latest_trades_doge = api.trades_latest_data_symbol('BITTREX_SPOT_BTC_USD') + +for data in latest_trades_doge: + print('Symbol ID: %s' % data['symbol_id']) + print('Time Exchange: %s' % data['time_exchange']) + print('Time CoinAPI: %s' % data['time_coinapi']) + print('UUID: %s' % data['uuid']) + print('Price: %s' % data['price']) + print('Size: %s' % data['size']) + print('Taker Side: %s' % data['taker_side']) + +historical_trades_btc = api.trades_historical_data('BITSTAMP_SPOT_BTC_USD', {'time_start': start_of_2016}) + +for data in historical_trades_btc: + print('Symbol ID: %s' % data['symbol_id']) + print('Time Exchange: %s' % data['time_exchange']) + print('Time CoinAPI: %s' % data['time_coinapi']) + print('UUID: %s' % data['uuid']) + print('Price: %s' % data['price']) + print('Size: %s' % data['size']) + print('Taker Side: %s' % data['taker_side']) + +current_quotes = api.quotes_current_data_all() +print(current_quotes) +for quote in current_quotes: + print('Symbol ID: %s' % quote['symbol_id']) + print('Time Exchange: %s' % quote['time_exchange']) + print('Time CoinAPI: %s' % quote['time_coinapi']) + print('Ask Price: %s' % quote['ask_price']) + print('Ask Size: %s' % quote['ask_size']) + print('Bid Price: %s' % quote['bid_price']) + print('Bid Size: %s' % quote['bid_size']) + if 'last_trade' in quote: + print('Last Trade: %s' % quote['last_trade']) + +current_quote_btc_usd = api.quotes_current_data_symbol('BITSTAMP_SPOT_BTC_USD') + +print('Symbol ID: %s' % current_quote_btc_usd['symbol_id']) +print('Time Exchange: %s' % current_quote_btc_usd['time_exchange']) +print('Time CoinAPI: %s' % current_quote_btc_usd['time_coinapi']) +print('Ask Price: %s' % current_quote_btc_usd['ask_price']) +print('Ask Size: %s' % current_quote_btc_usd['ask_size']) +print('Bid Price: %s' % current_quote_btc_usd['bid_price']) +print('Bid Size: %s' % current_quote_btc_usd['bid_size']) +if 'last_trade' in current_quote_btc_usd: + last_trade = current_quote_btc_usd['last_trade'] + print('Last Trade:') + print('- Taker Side: %s' % last_trade['taker_side']) + print('- UUID: %s' % last_trade['uuid']) + print('- Time Exchange: %s' % last_trade['time_exchange']) + print('- Price: %s' % last_trade['price']) + print('- Size: %s' % last_trade['size']) + print('- Time CoinAPI: %s' % last_trade['time_coinapi']) + +quotes_latest_data = api.quotes_latest_data_all() + +for quote in quotes_latest_data: + print('Symbol ID: %s' % quote['symbol_id']) + print('Time Exchange: %s' % quote['time_exchange']) + print('Time CoinAPI: %s' % quote['time_coinapi']) + print('Ask Price: %s' % quote['ask_price']) + print('Ask Size: %s' % quote['ask_size']) + print('Bid Price: %s' % quote['bid_price']) + print('Bid Size: %s' % quote['bid_size']) + +quotes_latest_data_btc_usd = api.quotes_latest_data_symbol('BITSTAMP_SPOT_BTC_USD') + +for quote in quotes_latest_data_btc_usd: + print('Symbol ID: %s' % quote['symbol_id']) + print('Time Exchange: %s' % quote['time_exchange']) + print('Time CoinAPI: %s' % quote['time_coinapi']) + print('Ask Price: %s' % quote['ask_price']) + print('Ask Size: %s' % quote['ask_size']) + print('Bid Price: %s' % quote['bid_price']) + print('Bid Size: %s' % quote['bid_size']) + +quotes_historical_data_btc_usd = api.quotes_historical_data('BITSTAMP_SPOT_BTC_USD', {'time_start': start_of_2016}) + +for quote in quotes_historical_data_btc_usd: + print('Symbol ID: %s' % quote['symbol_id']) + print('Time Exchange: %s' % quote['time_exchange']) + print('Time CoinAPI: %s' % quote['time_coinapi']) + print('Ask Price: %s' % quote['ask_price']) + print('Ask Size: %s' % quote['ask_size']) + print('Bid Price: %s' % quote['bid_price']) + print('Bid Size: %s' % quote['bid_size']) + +# orderbooks_current_data = api.orderbooks_current_data_all() + +# for data in orderbooks_current_data: +# print('Symbol ID: %s' % data['symbol_id']) +# print('Time Exchange: %s' % data['time_exchange']) +# print('Time CoinAPI: %s' % data['time_coinapi']) +# print('Asks:') +# for ask in data['asks']: +# print('- Price: %s' % ask['price']) +# print('- Size: %s' % ask['size']) +# print('Bids:') +# for bid in data['bids']: +# print('- Price: %s' % bid['price']) +# print('- Size: %s' % bid['size']) + +orderbooks_current_data_btc_usd = api.orderbooks_current_data_symbol('BITSTAMP_SPOT_BTC_USD') + +print('Symbol ID: %s' % orderbooks_current_data_btc_usd['symbol_id']) +print('Time Exchange: %s' % orderbooks_current_data_btc_usd['time_exchange']) +print('Time CoinAPI: %s' % orderbooks_current_data_btc_usd['time_coinapi']) +print('Asks:') +for ask in orderbooks_current_data_btc_usd['asks']: + print('- Price: %s' % ask['price']) + print('- Size: %s' % ask['size']) +print('Bids:') +for bid in orderbooks_current_data_btc_usd['bids']: + print('- Price: %s' % bid['price']) + print('- Size: %s' % bid['size']) + +orderbooks_latest_data_btc_usd = api.orderbooks_latest_data('BITSTAMP_SPOT_BTC_USD') + +for data in orderbooks_latest_data_btc_usd: + print('Symbol ID: %s' % data['symbol_id']) + print('Time Exchange: %s' % data['time_exchange']) + print('Time CoinAPI: %s' % data['time_coinapi']) + print('Asks:') + for ask in data['asks']: + print('- Price: %s' % ask['price']) + print('- Size: %s' % ask['size']) + print('Bids:') + for bid in data['bids']: + print('- Price: %s' % bid['price']) + print('- Size: %s' % bid['size']) + +orderbooks_historical_data_btc_usd = api.orderbooks_historical_data('BITSTAMP_SPOT_BTC_USD', {'time_start': start_of_2016}) + +for data in orderbooks_historical_data_btc_usd: + print('Symbol ID: %s' % data['symbol_id']) + print('Time Exchange: %s' % data['time_exchange']) + print('Time CoinAPI: %s' % data['time_coinapi']) + print('Asks:') + for ask in data['asks']: + print('- Price: %s' % ask['price']) + print('- Size: %s' % ask['size']) + print('Bids:') + for bid in data['bids']: + print('- Price: %s' % bid['price']) + print('- Size: %s' % bid['size']) + diff --git a/data-api/python-rest/coinapi_rest_v1/restapi.py b/data-api/python-rest/coinapi_rest_v1/restapi.py new file mode 100644 index 0000000000..51dd9893e5 --- /dev/null +++ b/data-api/python-rest/coinapi_rest_v1/restapi.py @@ -0,0 +1,347 @@ +import urllib.request +import urllib.parse +import gzip +import json + +PRODUCTION_URL = 'https://rest.coinapi.io/v1%s' + +class HTTPClient: + def __init__(self, endpoint, headers = dict(), params = dict()): + self.url = PRODUCTION_URL % endpoint + self.params = params + self.headers = headers + + def perform(self): + resource = self.url + + if self.params: + query_string = urllib.parse.urlencode(self.params) + resource = '%s?%s' % (self.url, query_string) + + request = urllib.request.Request(resource, headers=self.headers) + handler = urllib.request.urlopen(request) + raw_response = handler.read() + + if 'Accept-Encoding' in self.headers: + if self.headers['Accept-Encoding'] == 'deflate, gzip': + raw_response = gzip.decompress(raw_response) + + encoding = handler.info().get_content_charset('utf-8') + response = json.loads(raw_response.decode(encoding)) + return response + +class MetadataListExchangesRequest: + def endpoint(self): + return '/exchanges' + +class MetadataListAssetsRequest: + def endpoint(self): + return '/assets' + +class MetadataListSymbolsRequest: + def __init__(self, query_parameters = dict()): + self.query_parameters = query_parameters + + def endpoint(self): + return '/symbols' + +class ExchangeRatesGetSpecificRateRequest: + def __init__(self, + asset_id_base, + asset_id_quote, + query_parameters = dict()): + self.asset_id_base = asset_id_base + self.asset_id_quote = asset_id_quote + self.query_parameters = query_parameters + + def endpoint(self): + return '/exchangerate/%s/%s' % ( + self.asset_id_base, + self.asset_id_quote) + +class ExchangeRatesGetAllCurrentRates: + def __init__(self, asset_id_base): + self.asset_id_base = asset_id_base + + def endpoint(self): + return '/exchangerate/%s' % self.asset_id_base + +class OHLCVListAllPeriodsRequest: + def endpoint(self): + return '/ohlcv/periods' + +class OHLCVLatestDataRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/ohlcv/%s/latest' % self.symbol_id + +class OHLCVHistoricalDataRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/ohlcv/%s/history' % self.symbol_id + +class TradesLatestDataAllRequest: + def __init__(self, query_parameters = dict()): + self.query_parameters = query_parameters + + def endpoint(self): + return '/trades/latest' + +class TradesLatestDataSymbolRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/trades/%s/latest' % self.symbol_id + +class TradesHistoricalDataRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/trades/%s/history' % self.symbol_id + +class QuotesCurrentDataAllRequest: + def endpoint(self): + return '/quotes/current' + +class QuotesCurrentDataSymbolRequest: + def __init__(self, symbol_id): + self.symbol_id = symbol_id + + def endpoint(self): + return '/quotes/%s/current' % self.symbol_id + +class QuotesLatestDataAllRequest: + def __init__(self, query_parameters = dict()): + self.query_parameters = query_parameters + + def endpoint(self): + return '/quotes/latest' + +class QuotesLatestDataSymbolRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/quotes/%s/latest' % self.symbol_id + + def limit(self, lim): + params = self.__with_parameter('limit', lim) + return QuotesLatestDataSymbolRequest(self.symbol_id, params) + only = limit + +class QuotesHistoricalData: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/quotes/%s/history' % self.symbol_id + +class OrderbooksCurrentDataAllRequest: + def endpoint(self): + return '/orderbooks/current' + +class OrderbooksCurrentDataSymbolRequest: + def __init__(self, symbol_id): + self.symbol_id = symbol_id + + def endpoint(self): + return '/orderbooks/%s/current' % self.symbol_id + +class OrderbooksLatestDataRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/orderbooks/%s/latest' % self.symbol_id + +class OrderbooksHistoricalDataRequest: + def __init__(self, symbol_id, query_parameters = dict()): + self.symbol_id = symbol_id + self.query_parameters = query_parameters + + def endpoint(self): + return '/orderbooks/%s/history' % self.symbol_id + +class CoinAPIv1: + DEFAULT_HEADERS = { + 'Accept': 'application/json' + } + def __init__(self, api_key, headers = dict(), client_class=HTTPClient): + self.api_key = api_key + header_apikey = {'X-CoinAPI-Key': self.api_key} + self.headers = {**self.DEFAULT_HEADERS, **headers, **header_apikey} + self.client_class = client_class + + def with_header(self, header, value): + old_headers = self.headers + new_header = {header: value} + return CoinAPIv1(self.api_key, {**old_headers, **new_header}) + + def with_headers(self, additional_headers): + old_headers = self.headers + return CoinAPIv1(self.api_key, {**old_headers, **additional_headers}) + + def metadata_list_exchanges(self): + request = MetadataListExchangesRequest() + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def metadata_list_assets(self): + request = MetadataListAssetsRequest() + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def metadata_list_symbols(self, query_parameters = dict()): + request = MetadataListSymbolsRequest(query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def exchange_rates_get_specific_rate(self, + asset_id_base, + asset_id_quote, + query_parameters = dict()): + request = ExchangeRatesGetSpecificRateRequest(asset_id_base, + asset_id_quote, + query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def exchange_rates_get_all_current_rates(self, + asset_id_base): + request = ExchangeRatesGetAllCurrentRates(asset_id_base) + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def ohlcv_list_all_periods(self): + request = OHLCVListAllPeriodsRequest() + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def ohlcv_latest_data(self, + symbol_id, + query_parameters = dict()): + request = OHLCVLatestDataRequest(symbol_id, + query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def ohlcv_historical_data(self, + symbol_id, + query_parameters): + request = OHLCVHistoricalDataRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def trades_latest_data_all(self, + query_parameters = dict()): + request = TradesLatestDataAllRequest(query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def trades_latest_data_symbol(self, + symbol_id, + query_parameters = dict()): + request = TradesLatestDataSymbolRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def trades_historical_data(self, + symbol_id, + query_parameters = dict()): + request = TradesHistoricalDataRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def quotes_current_data_all(self): + request = QuotesCurrentDataAllRequest() + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def quotes_current_data_symbol(self, + symbol_id): + request = QuotesCurrentDataSymbolRequest(symbol_id) + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def quotes_latest_data_all(self, + query_parameters = dict()): + request = QuotesLatestDataAllRequest(query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def quotes_latest_data_symbol(self, + symbol_id, + query_parameters = dict()): + request = QuotesLatestDataSymbolRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def quotes_historical_data(self, + symbol_id, + query_parameters = dict()): + request = QuotesHistoricalData(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def orderbooks_current_data_all(self): + request = OrderbooksCurrentDataAllRequest() + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def orderbooks_current_data_symbol(self, + symbol_id): + request = OrderbooksCurrentDataSymbolRequest(symbol_id) + client = self.client_class(request.endpoint(), self.headers) + return client.perform() + + def orderbooks_latest_data(self, + symbol_id, + query_parameters = dict()): + request = OrderbooksLatestDataRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + + def orderbooks_historical_data(self, + symbol_id, + query_parameters = dict()): + request = OrderbooksHistoricalDataRequest(symbol_id, query_parameters) + client = self.client_class(request.endpoint(), + self.headers, + request.query_parameters) + return client.perform() + diff --git a/data-api/python-rest/setup.py b/data-api/python-rest/setup.py new file mode 100644 index 0000000000..c6f3219054 --- /dev/null +++ b/data-api/python-rest/setup.py @@ -0,0 +1,22 @@ +import setuptools + +with open("README.md", "r") as fh: + long_description = fh.read() + +setuptools.setup( + name="coinapi.rest.v1", + version="1.3", + author="Tomasz Przybysz", + author_email="tom.przybysz@gmail.com", + description="SDKs for CoinAPI", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://docs.coinapi.io/", + packages=setuptools.find_packages(), + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + ], + python_requires='>=3.0', +) diff --git a/data-api/python-ws/README.md b/data-api/python-ws/README.md new file mode 100644 index 0000000000..a190b93f04 --- /dev/null +++ b/data-api/python-ws/README.md @@ -0,0 +1,9 @@ +To run examples: + +```bash +git clone https://github.com/coinapi/coinapi-sdk/ +cd coinapi-sdk/data-api/python-ws +# edit examples.py, fill your API key inside of it +pip install websocket-client +python examples.py +``` diff --git a/data-api/python-ws/examples.py b/data-api/python-ws/examples.py new file mode 100644 index 0000000000..638301e696 --- /dev/null +++ b/data-api/python-ws/examples.py @@ -0,0 +1,20 @@ +from websocket import create_connection +import json + +test_key = 'YOUR_API_KEY' + +class CoinAPIv1_subscribe(object): + def __init__(self, apikey): + self.type = "hello" + self.apikey = apikey + self.heartbeat = True + self.subscribe_data_type = ["trade", "quote", "book20"] + +ws = create_connection("wss://ws.coinapi.io/v1") +sub = CoinAPIv1_subscribe(test_key) +ws.send(json.dumps(sub.__dict__)) +while True: + msg = ws.recv() + print(msg) + +ws.close() diff --git a/data-api/r-rest-2/DESCRIPTION b/data-api/r-rest-2/DESCRIPTION new file mode 100644 index 0000000000..1bdbea5830 --- /dev/null +++ b/data-api/r-rest-2/DESCRIPTION @@ -0,0 +1,23 @@ +Package: rcoinapi +Title: What the Package Does (One Line, Title Case) +Version: 0.0.0.9000 +Authors@R: + person(given = "Ramshreyas", + family = "Rao", + role = c("aut", "cre"), + email = "ramshreyas.rao@gmail.com", + comment = c(ORCID = "YOUR-ORCID-ID")) +Description: R package for the CoinAPI API. Designed to give outputs similar to quantmod when it comes to OHLCV data. Requires an API key from coinapi.io - the Author is not responsible for the quality of the data! +License: MIT + file LICENSE +Encoding: UTF-8 +LazyData: true +Roxygen: list(markdown = TRUE) +RoxygenNote: 7.1.1.9001 +Suggests: + testthat (>= 3.0.0) +Config/testthat/edition: 3 +Imports: + lubridate, + httr, + jsonlite, + xts diff --git a/data-api/r-rest-2/R/ExchangeRates.R b/data-api/r-rest-2/R/ExchangeRates.R new file mode 100644 index 0000000000..9b4beb9521 --- /dev/null +++ b/data-api/r-rest-2/R/ExchangeRates.R @@ -0,0 +1,105 @@ +#' Get exchange rate for a base/quote pair +#' +#' @param assetIdBase +#' @param assetIdQuote +#' @param time +#' +#' @return +#' @export +#' +#' @examples +#' getExchangeRate("BTC", "USD") +getExchangeRate <- function(assetIdBase, + assetIdQuote, + time = NULL) { + + endpoint <- paste0(EXCHANGERATE_ENDPOINT, assetIdBase, "/", assetIdQuote) + + if(is.null(time)) { + + executeRequest("GET", endpoint) + + } else { + + executeRequest("GET", endpoint, params = list("time" = time)) + + } + +} + +#' Get all exchange rates for a symbol +#' +#' @param assetIdBase +#' @param invert +#' @param filter_asset_id +#' +#' @return +#' @export +#' +#' @examples +#' getAllExchangeRates("BTC") +getAllExchangeRates <- function(assetIdBase, + invert = FALSE, + filter_asset_id = NULL) { + + endpoint <- paste0(EXCHANGERATE_ENDPOINT, assetIdBase) + + if(invert) inv <- "true" else inv <- "false" + + if(is.null(filter_asset_id)) { + + executeRequest("GET", endpoint, params = list("invert" = inv)) + + } else { + + executeRequest("GET", endpoint, params = list("invert" = inv, "filter_asset_id" = listToStringArray(filter_asset_id))) + + } + +} + +#' Get valid periods for historical exchange rates queries +#' +#' @return +#' @export +#' +#' @examples +#' getHIstoricalExchangeRatePeriods() +getHistoricalExchangeRatePeriods <- function() { + + endpoint <- paste0(EXCHANGERATE_ENDPOINT, "history/periods") + + executeRequest("GET", endpoint) + +} + +#' Get the historical exchange rates between two assets as an XTS object +#' +#' @param assetIdBase +#' @param assetIdQuote +#' @param periodId +#' @param timeStart +#' @param timeEnd +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getHistoricalExchangeRates("BTC", "USD", "1HRS", "2016-01-01T00:00:00", "2016-02-01T00:00:00", limit = 25) +getHistoricalExchangeRates <- function(assetIdBase, + assetIdQuote, + periodId, + timeStart, + timeEnd, + limit = 100) { + + symbolName <- paste0(assetIdBase, "/", assetIdQuote) + + endpoint <- paste0(EXCHANGERATE_ENDPOINT, assetIdBase, "/", assetIdQuote, "/history") + + xtsData <- executeXtsRequest("GET", endpoint, params = list("period_id" = periodId, "time_start" = timeStart, "time_end" = timeEnd, "limit" = as.character(limit))) + + renameOHLCVColumns(xtsData, symbolName) + +} diff --git a/data-api/r-rest-2/R/Markets.R b/data-api/r-rest-2/R/Markets.R new file mode 100644 index 0000000000..146efada35 --- /dev/null +++ b/data-api/r-rest-2/R/Markets.R @@ -0,0 +1,125 @@ +#' Get list of all exchanges provided by CoinAPI +#' +#' @param exchangeId +#' +#' @return +#' @export +#' +#' @examples +#' getExchanges() +#' getExchanges("FTX") +getExchanges <- function(exchangeId = NULL) { + + if(is.list(exchangeId)) { + + endpoint <- EXCHANGES_ENDPOINT + + executeRequest("GET", endpoint, params = list("filter_exchange_id" = listToStringArray(exchangeId))) + + } else { + + endpoint <- paste0(EXCHANGES_ENDPOINT, exchangeId) + + executeRequest("GET", endpoint) + + } + +} + +#' Get URLs of all exchange icons by size +#' +#' @param sizeText +#' +#' @return +#' @export +#' +#' @examples +#' getExchangeIcons(32) +getExchangeIcons <- function(sizeText) { + + endpoint <- paste0(EXCHANGES_ENDPOINT, "icons/", sizeText) + + executeRequest("GET", endpoint) + +} + +#' Get all Assets listed by CoinAPI +#' +#' @param assetId +#' +#' @return +#' @export +#' +#' @examples +#' getAssets() +#' getAssets("BTC") +getAssets <- function(assetId = NULL) { + + if(is.list(assetId)) { + + endpoint <- ASSETS_ENDPOINT + + executeRequest("GET", endpoint, params = list("filter_asset_id" = listToStringArray(assetId))) + + } else { + + endpoint <- paste0(ASSETS_ENDPOINT, assetId) + + executeRequest("GET", endpoint) + + } + +} + +#' Get icon URLs for all listed Assets +#' +#' @param sizeText +#' +#' @return +#' @export +#' +#' @examples +#' getAssetIcons(32) +getAssetIcons <- function(sizeText) { + + endpoint <- paste0(ASSETS_ENDPOINT, "icons/", sizeText) + + executeRequest("GET", endpoint) + +} + +#' Get all symbols listed by CoinAPI - named to not clash with Quantmod +#' +#' @param symbolId +#' @param exchangeId +#' @param assetId +#' +#' @return +#' @export +#' +#' @examples +#' getCryptoSymbols() +#' getCryptoSymbols(filterSymbolId = "BTC") +#' getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD") +#' getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD", exchangeId = "FTX") +getCryptoSymbols <- function(filterSymbolId = NULL, + exchangeId = NULL, + filterAssetId = NULL) { + + if(is.list(filterSymbolId) & is.list(exchangeId) & is.list(filterAssetId)) { + + endpoint <- SYMBOLS_ENDPOINT + + executeRequest("GET", endpoint, params = list("filter_symbol_id" = listToStringArray(filterSymbolId), + "filter_exchange_id" = listToStringArray(exchangeId), + "filter_asset_id" = listToStringArray(filterAssetId))) + + } else { + + endpoint <- paste0(SYMBOLS_ENDPOINT, exchangeId) + + executeRequest("GET", endpoint) + + } + +} diff --git a/data-api/r-rest-2/R/OHLCV.R b/data-api/r-rest-2/R/OHLCV.R new file mode 100644 index 0000000000..794e73e6b8 --- /dev/null +++ b/data-api/r-rest-2/R/OHLCV.R @@ -0,0 +1,117 @@ +#' Get valid period Ids for OHLCV requests +#' +#' @return +#' @export +#' +#' @examples +#' getOHLCVPeriods() +getOHLCVPeriods <- function() { + + endpoint <- paste0(OHLCV_ENDPOINT, "periods") + + executeRequest("GET", endpoint) + +} + +#' Get OHLCV latest timeseries data returned in time descending order. Data can be requested by the period and symbol or asset pairs. +#' If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT markets which +#' contain both assets in any order. +#' +#' @param assetIdBase +#' @param assetIdQuote +#' @param periodId +#' @param includeEmptyItems +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getLatestOHLCV("BITSTAMP_SPOT_BTC_USD", "1MIN", limit = 25) +#' getLatestOHLCV("BTC", "USD", periodId = "1MIN", limit = 25) +getLatestOHLCV <- function(assetIdBase, + assetIdQuote = NULL, + periodId, + includeEmptyItems = FALSE, + limit = 100) { + + if(is.null(assetIdQuote)) { + + symbolName <- assetIdBase + + endpoint <- paste0(OHLCV_ENDPOINT, assetIdBase, "/latest") + + } else { + + symbolName <- paste0(assetIdBase, "_", assetIdQuote) + + endpoint <- paste0(OHLCV_ENDPOINT, assetIdBase, "/", assetIdQuote, "/latest") + + } + + xtsData <- executeXtsRequest("GET", endpoint, params = list("period_id" = periodId, "limit" = as.character(limit), "include_empty_items" = includeEmptyItems)) + + data <- renameOHLCVColumns(xtsData, symbolName) + + assign(symbolName, data, envir = .GlobalEnv) + + symbolName + +} + +#' Get OHLCV timeseries data returned in time ascending order. Data can be requested by the period and symbol or asset pairs. +#' If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT +#' markets which contain both assets in any order.. +#' +#' @param assetIdBase +#' @param assetIdQuote +#' @param periodId +#' @param timeStart +#' @param timeEnd +#' @param includeEmptyItems +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getHistoricalOHLCV("BTC", "USD", periodId = "1MIN", timeStart = "2016-01-01T00:00:00", limit = 25) +getHistoricalOHLCV <- function(assetIdBase, + assetIdQuote = NULL, + periodId, + timeStart, + timeEnd = NULL, + includeEmptyItems = FALSE, + limit = 100) { + + if(is.null(assetIdQuote)) { + + symbolName <- assetIdBase + + endpoint <- paste0(OHLCV_ENDPOINT, assetIdBase, "/history") + + } else { + + symbolName <- paste0(assetIdBase, "_", assetIdQuote) + + endpoint <- paste0(OHLCV_ENDPOINT, assetIdBase, "/", assetIdQuote, "/history") + + } + + if(is.null(timeEnd)) { + + xtsData <- executeXtsRequest("GET", endpoint, params = list("period_id" = periodId, "time_start" = timeStart, "limit" = as.character(limit), "include_empty_items" = includeEmptyItems)) + + } else { + + xtsDate <- executeXtsRequest("GET", endpoint, params = list("period_id" = periodId, "time_start" = timeStart, "time_end" = timeEnd, "limit" = as.character(limit), "include_empty_items" = includeEmptyItems)) + + } + + data <- renameOHLCVColumns(xtsData, symbolName) + + assign(symbolName, data, envir = .GlobalEnv) + + symbolName + +} diff --git a/data-api/r-rest-2/R/Orderbook.R b/data-api/r-rest-2/R/Orderbook.R new file mode 100644 index 0000000000..0559b54b30 --- /dev/null +++ b/data-api/r-rest-2/R/Orderbook.R @@ -0,0 +1,81 @@ +#' Get current order book snapshot for all or a specific symbol. +#' +#' @param symbol +#' @param filterSymbol +#' @param limitLevels +#' +#' @return +#' @export +#' +#' @examples +#' getOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1) +#' getOrderbook(filterSymbol = "BTC") +getOrderbook <- function(symbol = NULL, + filterSymbol = NULL, + limitLevels = 0) { + + if(is.null(symbol)) { + + endpoint <- paste0(ORDERBOOK_ENDPOINT, "current") + + p <- list("filter_symbol_id" = filterSymbol, "limit_levels" = limitLevels) + + } else { + + endpoint <- paste0(QUOTES_ENDPOINT, symbol, "/current") + + p <- list("limit_levels" = limitLevels) + + } + + executeRequest("GET", endpoint, params = p) + +} + +#' Get latest order book snapshots for a specific symbol, returned in time descending order. +#' +#' @param symbol +#' @param limitLevels +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getLatestOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1, limit = 25) +getLatestOrderbook <- function(symbol, + limitLevels = 0, + limit = 100) { + + endpoint <- paste0(ORDERBOOK_ENDPOINT, symbol, "/latest") + + executeRequest("GET", endpoint, params = list("limit" = limit, "limit_levels" = limitLevels)) + +} + +#' Get historical order book snapshots for a specific symbol within time range, returned in time ascending order. +#' +#' @param symbol +#' @param limitLevels +#' @param timeStart +#' @param timeEnd +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getHistoricalOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limitLevels = 1, limit = 25) +getHistoricalOrderbook <- function(symbol, + limitLevels = 0, + timeStart, + timeEnd = NULL, + limit = 100) { + + endpoint <- paste0(ORDERBOOK_ENDPOINT, symbol, "/history") + + p <- list("time_start" = timeStart, "time_end" = timeEnd, "limit" = limit, "limit_levels" = limitLevels) + + executeRequest("GET", endpoint, params = p) + +} diff --git a/data-api/r-rest-2/R/OrderbookL3.R b/data-api/r-rest-2/R/OrderbookL3.R new file mode 100644 index 0000000000..22b4e6fc6c --- /dev/null +++ b/data-api/r-rest-2/R/OrderbookL3.R @@ -0,0 +1,33 @@ +#' Get current order book snapshot for all or a specific symbol. +#' +#' @param symbol +#' @param filterSymbol +#' @param limitLevels +#' +#' @return +#' @export +#' +#' @examples +#' getOrderbookL3(filterSymbol = "BTC", limitLevels = 1) +#' getOrderbookL3(symbol = "COINBASE_SPOT_BCH_USD", limitLevels = 1) +getOrderbookL3 <- function(symbol = NULL, + filterSymbol = NULL, + limitLevels = 0) { + + if(is.null(symbol)) { + + endpoint <- paste0(ORDERBOOKL3_ENDPOINT, "current") + + p <- list("filter_symbol_id" = filterSymbol, "limit_levels" = limitLevels) + + } else { + + endpoint <- paste0(QUOTES_ENDPOINT, symbol, "/current") + + p <- list("limit_levels" = limitLevels) + + } + + executeRequest("GET", endpoint, params = p) + +} diff --git a/data-api/r-rest-2/R/Quotes.R b/data-api/r-rest-2/R/Quotes.R new file mode 100644 index 0000000000..bdc286c82d --- /dev/null +++ b/data-api/r-rest-2/R/Quotes.R @@ -0,0 +1,89 @@ +#' Get current quotes for all symbols or for a specific symbol. +#' +#' @param symbol +#' @param filterSymbol +#' +#' @return +#' @export +#' +#' @examples +#' getQuotes() +#' getQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +#' getQuotes(filterSymbol = "BTC") +getQuotes <- function(symbol = NULL, + filterSymbol = NULL) { + + if(is.null(symbol)) { + + endpoint <- paste0(QUOTES_ENDPOINT, "current") + + executeRequest("GET", endpoint, params = list("filter_symbol_id" = filterSymbol)) + + } else { + + endpoint <- paste0(QUOTES_ENDPOINT, symbol, "/current") + + executeRequest("GET", endpoint) + + } + +} + +#' Get latest quote updates up to 1 minute ago or get updates for a specific symbol without time limit. +#' Latest data is always returned in time descending order. +#' +#' @param symbol +#' @param filterSymbol +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getLatestQuotes() +#' getLatestQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +#' getLatestQuotes(filterSymbol = "BTC") +getLatestQuotes <- function(symbol = NULL, + filterSymbol = NULL, + limit = 100) { + + if(is.null(symbol)) { + + endpoint <- paste0(QUOTES_ENDPOINT, "latest") + + executeRequest("GET", endpoint, params = list("filter_symbol_id" = filterSymbol, "limit" = limit)) + + } else { + + endpoint <- paste0(QUOTES_ENDPOINT, symbol, "/latest") + + executeRequest("GET", endpoint, params = list("limit" = limit)) + + } + +} + +#' Get historical quote updates within requested time range, returned in time ascending order. +#' +#' @param symbol +#' @param timeStart +#' @param timeEnd +#' @param limit +#' +#' @return +#' @export +#' +#' @examples +#' getHistoricalQuotes(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +getHistoricalQuotes <- function(symbol, + timeStart, + timeEnd = NULL, + limit = 100) { + + endpoint <- paste0(QUOTES_ENDPOINT, symbol, "/history") + + p <- list("time_start" = timeStart, "time_end" = timeEnd, "limit" = limit) + + executeXtsRequest("GET", endpoint, params = p, indexBy = "time_exchange") + +} diff --git a/data-api/r-rest-2/R/Trades.R b/data-api/r-rest-2/R/Trades.R new file mode 100644 index 0000000000..25a2bec095 --- /dev/null +++ b/data-api/r-rest-2/R/Trades.R @@ -0,0 +1,73 @@ +#' Get latest trades from all symbols up to 1 minute ago or get latest trades from a specific symbol without time limitation. Latest data is always returned in time descending order. +#' +#' @param symbol +#' @param limit +#' @param filterSymbol +#' @param include +#' +#' @return +#' @export +#' +#' @examples +#' getTrades() +#' getTrades(filterSymbol = "BTC", limit = 25) +#' getTrades(symbol = "BITSTAMP_SPOT_BTC_USD", limit = 25) +getTrades <- function(symbol = NULL, + limit = 100, + filterSymbol = NULL, + include = FALSE) { + + if(is.null(symbol)) { + + endpoint <- paste0(TRADES_ENDPOINT, "latest") + + if(is.null(filterSymbol)) { + + p <- list("limit" = limit) + + } else { + + p <- list("limit" = limit, "filter_symbol_id" = filterSymbol) + + } + + + } else { + + endpoint <- paste0(TRADES_ENDPOINT, symbol, "/latest") + + p <- list("limit" = limit, "include_id" = include) + + } + + executeRequest("GET", endpoint, params = p) + +} + +#' Get historical transactions from specific symbol, returned in time ascending order. +#' +#' @param symbol +#' @param timeStart +#' @param timeEnd +#' @param limit +#' @param include +#' +#' @return +#' @export +#' +#' @examples +#' getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", limit = 25) +#' getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +getHistoricalTrades <- function(symbol, + timeStart, + timeEnd = NULL, + limit = 100, + include = FALSE) { + + endpoint <- paste0(TRADES_ENDPOINT, symbol, "/history") + + p <- list("time_start" = timeStart, "time_end" = timeEnd, "limit" = limit, "include_id" = include) + + executeXtsRequest("GET", endpoint, params = p, indexBy = "time_exchange") + +} diff --git a/data-api/r-rest-2/R/config.R b/data-api/r-rest-2/R/config.R new file mode 100644 index 0000000000..0d2f0c56b8 --- /dev/null +++ b/data-api/r-rest-2/R/config.R @@ -0,0 +1,10 @@ +BASE_URL <- "https://rest.coinapi.io" +EXCHANGES_ENDPOINT <- "/v1/exchanges/" +ASSETS_ENDPOINT <- "/v1/assets/" +SYMBOLS_ENDPOINT <- "/v1/symbols/" +EXCHANGERATE_ENDPOINT <- "/v1/exchangerate/" +OHLCV_ENDPOINT <- "/v1/ohlcv/" +TRADES_ENDPOINT <- "/v1/trades/" +QUOTES_ENDPOINT <- "/v1/quotes/" +ORDERBOOK_ENDPOINT <- "/v1/orderbooks/" +ORDERBOOKL3_ENDPOINT <- "/v1/orderbooks3/" diff --git a/data-api/r-rest-2/R/utils.R b/data-api/r-rest-2/R/utils.R new file mode 100644 index 0000000000..6a927e1540 --- /dev/null +++ b/data-api/r-rest-2/R/utils.R @@ -0,0 +1,120 @@ +executeRequest <- function(method, path, params = NULL, body = NULL, retries = 0) { + + apiKey <- Sys.getenv("COIN_API_KEY") + + if(apiKey == "") stop("No API Key!! Please set CoinAPI key with setAPIKey()") + + url <- paste0(BASE_URL, path) + switch (method, + "GET" = res <- tryCatch( + + httr::GET(url, + query = params, + body, + httr::add_headers(`X-CoinAPI-Key` = apiKey) + ), + + error = function(e) e + + ), + + "POST" = res <- tryCatch( + + httr::GET(url, + query = params, + body, + httr::add_headers(`X-CoinAPI-Key` = apiKey) + ), + + error = function(e) e + + ), + + stop("Only 'GET' and 'POST' allowed") + + ) + + httr::stop_for_status(res) + + parseJSONResponse(res) + +} + +executeXtsRequest <- function(method, path, params = NULL, body = NULL, retries = 0, indexBy = "time_period_start") { + + res <- executeRequest(method, path, params, body, retries) + + xts::xts(res, order.by = lubridate::as_datetime(res[,indexBy])) + +} + +renameOHLCVColumns <- function(xtsObject, symbolName) { + + if(ncol(xtsObject) == 8) { + + colnames(xtsObject) <- c("time_period_start", + "time_period_end", + "time_open", + "time_close", + paste0(symbolName, ".Open"), + paste0(symbolName, ".High"), + paste0(symbolName, ".Low"), + paste0(symbolName, ".Close")) + + } else { + + colnames(xtsObject) <- c("time_period_start", + "time_period_end", + "time_open", + "time_close", + paste0(symbolName, ".Open"), + paste0(symbolName, ".High"), + paste0(symbolName, ".Low"), + paste0(symbolName, ".Close"), + paste0(symbolName, ".Volume"), + "trades_count") + + } + + xtsObject <- xtsObject[,c(5:9)] + + storage.mode(xtsObject) <- "numeric" + + xtsObject + +} + +listToStringArray <- function(l) { + + stringArray <- "" + + for (item in l) { + stringArray <- paste0(stringArray, item, ",") + } + + substr(stringArray, 1, nchar(stringArray) - 1) + +} + +#' Set your API Key +#' +#' @param apiKey +#' +#' @return +#' @export +#' +#' @examples +#' setApiKey(XXXXXXXXXXXXXXXX) +setApiKey <- function(apiKey) { + + Sys.setenv(COIN_API_KEY = apiKey) + +} + +parseJSONResponse <- function(res) { + + resText <- httr::content(res, as = "text") + + jsonlite::fromJSON(resText, flatten = TRUE) + +} diff --git a/data-api/r-rest-2/README.md b/data-api/r-rest-2/README.md new file mode 100644 index 0000000000..b932793cca --- /dev/null +++ b/data-api/r-rest-2/README.md @@ -0,0 +1,220 @@ + + + +# rcoinapi + + + + +R package for the CoinAPI.io REST API. + +Requires an API key: + +Documentation: + +## Installation + + + + + + +You can install the development version from +[GitHub](https://github.com/) with: + +``` r +install.packages("devtools") +library("devtools") +devtools::install_github("coinapi/coinapi-sdk", subdir="data-api/r-rest-2") +``` + +## Setup + +Load the library + +``` r +library(rcoinapi) +``` + +Set your API key (Get your API key at +) + +``` r +setApiKey("XXXXXXXXXXXXXXX") +``` + +## Usage + +# Metadata + +List all Exchanges, with details + +``` r +getExchanges() +getExchanges("FTX") +``` + +List all Exchange Icons + +``` r +getExchangeIcons(32) +``` + +List all Assets + +``` r +getAssets() +getAssets("BTC") +``` + +List all Asset Icons + +``` r +getAssetIcons(32) +``` + +List all Symbols + +``` r +getCryptoSymbols() +getCryptoSymbols(filterSymbolId = "BTC") +getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD") +getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD", exchangeId = "FTX") +``` + +# Exchange Rates + +Get exchange rate between pair of requested assets at specific or +current time. + +``` r +getExchangeRate("BTC", "USD") +``` + +Get the current exchange rate between requested asset and all other +assets. + +``` r +getAllExchangeRates("BTC") +``` + +Get valid periods for historical exchange rates queries + +``` r +getHistoricalExchangeRatePeriods() +``` + +Get the historical exchange rates between two assets as an XTS object +for a given time period + +``` r +getHistoricalExchangeRates("BTC", "USD", "1HRS", "2016-01-01T00:00:00", "2016-02-01T00:00:00", limit = 25) +``` + +# OHLCV + +Get valid period ids for OHLCV requests + +``` r +getOHLCVPeriods() +``` + +Get OHLCV latest timeseries data returned in time descending order. Data +can be requested by the period and symbol or asset pairs. If asset pairs +are used then timeseries in the response will contain data consolidated +across all most legitimate SPOT markets which contain both assets in any +order. + +``` r +getLatestOHLCV("BITSTAMP_SPOT_BTC_USD", periodId = "1MIN", limit = 25) +getLatestOHLCV("BTC", "USD", periodId = "1MIN", limit = 25) +``` + +Get OHLCV timeseries data returned in time ascending order. Data can be +requested by the period and symbol or asset pairs. If asset pairs are +used then timeseries in the response will contain data consolidated +across all most legitimate SPOT markets which contain both assets in any +order.. + +``` r +getHistoricalOHLCV("BTC", "USD", periodId = "1MIN", timeStart = "2016-01-01T00:00:00", limit = 25) +``` + +# Trades + +Get latest trades from all symbols up to 1 minute ago or get latest +trades from a specific symbol without time limitation. Latest data is +always returned in time descending order. + +``` r +getTrades() +getTrades(filterSymbol = "BTC", limit = 25) +getTrades(symbol = "BITSTAMP_SPOT_BTC_USD", limit = 25) +``` + +Get historical transactions from specific symbol, returned in time +ascending order. + +``` r +getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", limit = 25) +getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +``` + +# Quotes + +Get current quotes for all symbols or for a specific symbol. + +``` r +getQuotes() +getQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +getQuotes(filterSymbol = "BTC") +``` + +Get latest quote updates up to 1 minute ago or get updates for a +specific symbol without time limit. Latest data is always returned in +time descending order. + +``` r +getLatestQuotes() +#' getLatestQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +#' getLatestQuotes(filterSymbol = "BTC") +``` + +Get historical quote updates within requested time range, returned in +time ascending order. + +``` r +getHistoricalQuotes(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +``` + +# Orderbook + +Get current order book snapshot for all or a specific symbol. + +``` r +getOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1) +getOrderbook(filterSymbol = "BTC") +``` + +Get latest order book snapshots for a specific symbol, returned in time +descending order. + +``` r +getLatestOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1, limit = 25) +``` + +Get historical order book snapshots for a specific symbol within time +range, returned in time ascending order. + +``` r +getHistoricalOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limitLevels = 1, limit = 25) +``` + +# OrderbookL3 + +Get current order book snapshot for all or a specific symbol. + +``` r +getOrderbookL3(filterSymbol = "BTC", limitLevels = 1) +getOrderbookL3(symbol = "COINBASE_SPOT_BCH_USD", limitLevels = 1) +``` diff --git a/data-api/r-rest-2/man/figures/README-pressure-1.png b/data-api/r-rest-2/man/figures/README-pressure-1.png new file mode 100644 index 0000000000..c092055f2d Binary files /dev/null and b/data-api/r-rest-2/man/figures/README-pressure-1.png differ diff --git a/data-api/r-rest-2/man/getAllExchangeRates.Rd b/data-api/r-rest-2/man/getAllExchangeRates.Rd new file mode 100644 index 0000000000..0d47003d21 --- /dev/null +++ b/data-api/r-rest-2/man/getAllExchangeRates.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ExchangeRates.R +\name{getAllExchangeRates} +\alias{getAllExchangeRates} +\title{Get all exchange rates for a symbol} +\usage{ +getAllExchangeRates(assetIdBase, invert = FALSE, filter_asset_id = NULL) +} +\arguments{ +\item{filter_asset_id}{} +} +\value{ + +} +\description{ +Get all exchange rates for a symbol +} +\examples{ +getAllExchangeRates("BTC") +} diff --git a/data-api/r-rest-2/man/getAssetIcons.Rd b/data-api/r-rest-2/man/getAssetIcons.Rd new file mode 100644 index 0000000000..88fc96990b --- /dev/null +++ b/data-api/r-rest-2/man/getAssetIcons.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Markets.R +\name{getAssetIcons} +\alias{getAssetIcons} +\title{Get icon URLs for all listed Assets} +\usage{ +getAssetIcons(sizeText) +} +\arguments{ +\item{sizeText}{} +} +\value{ + +} +\description{ +Get icon URLs for all listed Assets +} +\examples{ +getAssetIcons(32) +} diff --git a/data-api/r-rest-2/man/getAssets.Rd b/data-api/r-rest-2/man/getAssets.Rd new file mode 100644 index 0000000000..60d4a865ce --- /dev/null +++ b/data-api/r-rest-2/man/getAssets.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Markets.R +\name{getAssets} +\alias{getAssets} +\title{Get all Assets listed by CoinAPI} +\usage{ +getAssets(assetId = NULL) +} +\arguments{ +\item{assetId}{} +} +\value{ + +} +\description{ +Get all Assets listed by CoinAPI +} +\examples{ +getAssets() +getAssets("BTC") +} diff --git a/data-api/r-rest-2/man/getCryptoSymbols.Rd b/data-api/r-rest-2/man/getCryptoSymbols.Rd new file mode 100644 index 0000000000..8d7e0206a2 --- /dev/null +++ b/data-api/r-rest-2/man/getCryptoSymbols.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Markets.R +\name{getCryptoSymbols} +\alias{getCryptoSymbols} +\title{Get all symbols listed by CoinAPI - named to not clash with Quantmod} +\usage{ +getCryptoSymbols( + filterSymbolId = NULL, + exchangeId = NULL, + filterAssetId = NULL +) +} +\arguments{ +\item{assetId}{} +} +\value{ + +} +\description{ +Get all symbols listed by CoinAPI - named to not clash with Quantmod +} +\examples{ +getCryptoSymbols() +getCryptoSymbols(filterSymbolId = "BTC") +getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD") +getCryptoSymbols(filterSymbolId = "BTC", filterAssetId = "USD", exchangeId = "FTX") +} diff --git a/data-api/r-rest-2/man/getExchangeIcons.Rd b/data-api/r-rest-2/man/getExchangeIcons.Rd new file mode 100644 index 0000000000..4411f8957f --- /dev/null +++ b/data-api/r-rest-2/man/getExchangeIcons.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Markets.R +\name{getExchangeIcons} +\alias{getExchangeIcons} +\title{Get URLs of all exchange icons by size} +\usage{ +getExchangeIcons(sizeText) +} +\arguments{ +\item{sizeText}{} +} +\value{ + +} +\description{ +Get URLs of all exchange icons by size +} +\examples{ +getExchangeIcons(32) +} diff --git a/data-api/r-rest-2/man/getExchangeRate.Rd b/data-api/r-rest-2/man/getExchangeRate.Rd new file mode 100644 index 0000000000..e969657618 --- /dev/null +++ b/data-api/r-rest-2/man/getExchangeRate.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ExchangeRates.R +\name{getExchangeRate} +\alias{getExchangeRate} +\title{Get exchange rate for a base/quote pair} +\usage{ +getExchangeRate(assetIdBase, assetIdQuote, time = NULL) +} +\arguments{ +\item{time}{} +} +\value{ + +} +\description{ +Get exchange rate for a base/quote pair +} +\examples{ +getExchangeRate("BTC", "USD") +} diff --git a/data-api/r-rest-2/man/getExchanges.Rd b/data-api/r-rest-2/man/getExchanges.Rd new file mode 100644 index 0000000000..75f261ce47 --- /dev/null +++ b/data-api/r-rest-2/man/getExchanges.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Markets.R +\name{getExchanges} +\alias{getExchanges} +\title{Get list of all exchanges provided by CoinAPI} +\usage{ +getExchanges(exchangeId = NULL) +} +\arguments{ +\item{exchangeId}{} +} +\value{ + +} +\description{ +Get list of all exchanges provided by CoinAPI +} +\examples{ +getExchanges() +getExchanges("FTX") +} diff --git a/data-api/r-rest-2/man/getHistoricalExchangeRatePeriods.Rd b/data-api/r-rest-2/man/getHistoricalExchangeRatePeriods.Rd new file mode 100644 index 0000000000..3cbcfa52ba --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalExchangeRatePeriods.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ExchangeRates.R +\name{getHistoricalExchangeRatePeriods} +\alias{getHistoricalExchangeRatePeriods} +\title{Get valid periods for historical exchange rates queries} +\usage{ +getHistoricalExchangeRatePeriods() +} +\value{ + +} +\description{ +Get valid periods for historical exchange rates queries +} +\examples{ +getHIstoricalExchangeRatePeriods() +} diff --git a/data-api/r-rest-2/man/getHistoricalExchangeRates.Rd b/data-api/r-rest-2/man/getHistoricalExchangeRates.Rd new file mode 100644 index 0000000000..d266895de9 --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalExchangeRates.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ExchangeRates.R +\name{getHistoricalExchangeRates} +\alias{getHistoricalExchangeRates} +\title{Get the historical exchange rates between two assets as an XTS object} +\usage{ +getHistoricalExchangeRates( + assetIdBase, + assetIdQuote, + periodId, + timeStart, + timeEnd, + limit = 100 +) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get the historical exchange rates between two assets as an XTS object +} +\examples{ +getHistoricalExchangeRates("BTC", "USD", "1HRS", "2016-01-01T00:00:00", "2016-02-01T00:00:00", limit = 25) +} diff --git a/data-api/r-rest-2/man/getHistoricalOHLCV.Rd b/data-api/r-rest-2/man/getHistoricalOHLCV.Rd new file mode 100644 index 0000000000..ae8019d353 --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalOHLCV.Rd @@ -0,0 +1,32 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/OHLCV.R +\name{getHistoricalOHLCV} +\alias{getHistoricalOHLCV} +\title{Get OHLCV timeseries data returned in time ascending order. Data can be requested by the period and symbol or asset pairs. +If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT +markets which contain both assets in any order..} +\usage{ +getHistoricalOHLCV( + assetIdBase, + assetIdQuote = NULL, + periodId, + timeStart, + timeEnd = NULL, + includeEmptyItems = FALSE, + limit = 100 +) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get OHLCV timeseries data returned in time ascending order. Data can be requested by the period and symbol or asset pairs. +If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT +markets which contain both assets in any order.. +} +\examples{ +getHistoricalOHLCV("BTC", "USD", periodId = "1MIN", timeStart = "2016-01-01T00:00:00", limit = 25) +} diff --git a/data-api/r-rest-2/man/getHistoricalOrderbook.Rd b/data-api/r-rest-2/man/getHistoricalOrderbook.Rd new file mode 100644 index 0000000000..49db84846e --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalOrderbook.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Orderbook.R +\name{getHistoricalOrderbook} +\alias{getHistoricalOrderbook} +\title{Get historical order book snapshots for a specific symbol within time range, returned in time ascending order.} +\usage{ +getHistoricalOrderbook( + symbol, + limitLevels = 0, + timeStart, + timeEnd = NULL, + limit = 100 +) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get historical order book snapshots for a specific symbol within time range, returned in time ascending order. +} +\examples{ +getHistoricalOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limitLevels = 1, limit = 25) +} diff --git a/data-api/r-rest-2/man/getHistoricalQuotes.Rd b/data-api/r-rest-2/man/getHistoricalQuotes.Rd new file mode 100644 index 0000000000..1866cd862c --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalQuotes.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Quotes.R +\name{getHistoricalQuotes} +\alias{getHistoricalQuotes} +\title{Get historical quote updates within requested time range, returned in time ascending order.} +\usage{ +getHistoricalQuotes(symbol, timeStart, timeEnd = NULL, limit = 100) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get historical quote updates within requested time range, returned in time ascending order. +} +\examples{ +getHistoricalQuotes(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +} diff --git a/data-api/r-rest-2/man/getHistoricalTrades.Rd b/data-api/r-rest-2/man/getHistoricalTrades.Rd new file mode 100644 index 0000000000..9b4b8db722 --- /dev/null +++ b/data-api/r-rest-2/man/getHistoricalTrades.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Trades.R +\name{getHistoricalTrades} +\alias{getHistoricalTrades} +\title{Get historical transactions from specific symbol, returned in time ascending order.} +\usage{ +getHistoricalTrades( + symbol, + timeStart, + timeEnd = NULL, + limit = 100, + include = FALSE +) +} +\arguments{ +\item{include}{} +} +\value{ + +} +\description{ +Get historical transactions from specific symbol, returned in time ascending order. +} +\examples{ +getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", limit = 25) +getHistoricalTrades(symbol = "BITSTAMP_SPOT_BTC_USD", timeStart = "2016-01-01T00:00:00", timeEnd = "2016-01-01T00:10:00", limit = 25) +} diff --git a/data-api/r-rest-2/man/getLatestOHLCV.Rd b/data-api/r-rest-2/man/getLatestOHLCV.Rd new file mode 100644 index 0000000000..05fac89035 --- /dev/null +++ b/data-api/r-rest-2/man/getLatestOHLCV.Rd @@ -0,0 +1,31 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/OHLCV.R +\name{getLatestOHLCV} +\alias{getLatestOHLCV} +\title{Get OHLCV latest timeseries data returned in time descending order. Data can be requested by the period and symbol or asset pairs. +If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT markets which +contain both assets in any order.} +\usage{ +getLatestOHLCV( + assetIdBase, + assetIdQuote = NULL, + periodId, + includeEmptyItems = FALSE, + limit = 100 +) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get OHLCV latest timeseries data returned in time descending order. Data can be requested by the period and symbol or asset pairs. +If asset pairs are used then timeseries in the response will contain data consolidated across all most legitimate SPOT markets which +contain both assets in any order. +} +\examples{ +getLatestOHLCV("BITSTAMP_SPOT_BTC_USD", "1MIN", limit = 25) +getLatestOHLCV("BTC", "USD", periodId = "1MIN", limit = 25) +} diff --git a/data-api/r-rest-2/man/getLatestOrderbook.Rd b/data-api/r-rest-2/man/getLatestOrderbook.Rd new file mode 100644 index 0000000000..e880481c45 --- /dev/null +++ b/data-api/r-rest-2/man/getLatestOrderbook.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Orderbook.R +\name{getLatestOrderbook} +\alias{getLatestOrderbook} +\title{Get latest order book snapshots for a specific symbol, returned in time descending order.} +\usage{ +getLatestOrderbook(symbol, limitLevels = 0, limit = 100) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get latest order book snapshots for a specific symbol, returned in time descending order. +} +\examples{ +getLatestOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1, limit = 25) +} diff --git a/data-api/r-rest-2/man/getLatestQuotes.Rd b/data-api/r-rest-2/man/getLatestQuotes.Rd new file mode 100644 index 0000000000..1f27c5a0cb --- /dev/null +++ b/data-api/r-rest-2/man/getLatestQuotes.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Quotes.R +\name{getLatestQuotes} +\alias{getLatestQuotes} +\title{Get latest quote updates up to 1 minute ago or get updates for a specific symbol without time limit. +Latest data is always returned in time descending order.} +\usage{ +getLatestQuotes(symbol = NULL, filterSymbol = NULL, limit = 100) +} +\arguments{ +\item{limit}{} +} +\value{ + +} +\description{ +Get latest quote updates up to 1 minute ago or get updates for a specific symbol without time limit. +Latest data is always returned in time descending order. +} +\examples{ +getLatestQuotes() +getLatestQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +getLatestQuotes(filterSymbol = "BTC") +} diff --git a/data-api/r-rest-2/man/getOHLCVPeriods.Rd b/data-api/r-rest-2/man/getOHLCVPeriods.Rd new file mode 100644 index 0000000000..92fb5d426f --- /dev/null +++ b/data-api/r-rest-2/man/getOHLCVPeriods.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/OHLCV.R +\name{getOHLCVPeriods} +\alias{getOHLCVPeriods} +\title{Get valid period Ids for OHLCV requests} +\usage{ +getOHLCVPeriods() +} +\value{ + +} +\description{ +Get valid period Ids for OHLCV requests +} +\examples{ +getOHLCVPeriods() +} diff --git a/data-api/r-rest-2/man/getOrderbook.Rd b/data-api/r-rest-2/man/getOrderbook.Rd new file mode 100644 index 0000000000..618c6d3312 --- /dev/null +++ b/data-api/r-rest-2/man/getOrderbook.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Orderbook.R +\name{getOrderbook} +\alias{getOrderbook} +\title{Get current order book snapshot for all or a specific symbol.} +\usage{ +getOrderbook(symbol = NULL, filterSymbol = NULL, limitLevels = 0) +} +\arguments{ +\item{limitLevels}{} +} +\value{ + +} +\description{ +Get current order book snapshot for all or a specific symbol. +} +\examples{ +getOrderbook(symbol = "BITSTAMP_SPOT_BTC_USD", limitLevels = 1) +getOrderbook(filterSymbol = "BTC") +} diff --git a/data-api/r-rest-2/man/getOrderbookL3.Rd b/data-api/r-rest-2/man/getOrderbookL3.Rd new file mode 100644 index 0000000000..dc6c07d935 --- /dev/null +++ b/data-api/r-rest-2/man/getOrderbookL3.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/OrderbookL3.R +\name{getOrderbookL3} +\alias{getOrderbookL3} +\title{Get current order book snapshot for all or a specific symbol.} +\usage{ +getOrderbookL3(symbol = NULL, filterSymbol = NULL, limitLevels = 0) +} +\arguments{ +\item{limitLevels}{} +} +\value{ + +} +\description{ +Get current order book snapshot for all or a specific symbol. +} +\examples{ +getOrderbookL3(filterSymbol = "BTC", limitLevels = 1) +getOrderbookL3(symbol = "COINBASE_SPOT_BCH_USD", limitLevels = 1) +} diff --git a/data-api/r-rest-2/man/getQuotes.Rd b/data-api/r-rest-2/man/getQuotes.Rd new file mode 100644 index 0000000000..e03230d497 --- /dev/null +++ b/data-api/r-rest-2/man/getQuotes.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Quotes.R +\name{getQuotes} +\alias{getQuotes} +\title{Get current quotes for all symbols or for a specific symbol.} +\usage{ +getQuotes(symbol = NULL, filterSymbol = NULL) +} +\arguments{ +\item{filterSymbol}{} +} +\value{ + +} +\description{ +Get current quotes for all symbols or for a specific symbol. +} +\examples{ +getQuotes() +getQuotes(symbol = "BITSTAMP_SPOT_BTC_USD") +getQuotes(filterSymbol = "BTC") +} diff --git a/data-api/r-rest-2/man/getTrades.Rd b/data-api/r-rest-2/man/getTrades.Rd new file mode 100644 index 0000000000..61ddb47620 --- /dev/null +++ b/data-api/r-rest-2/man/getTrades.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/Trades.R +\name{getTrades} +\alias{getTrades} +\title{Get latest trades from all symbols up to 1 minute ago or get latest trades from a specific symbol without time limitation. Latest data is always returned in time descending order.} +\usage{ +getTrades(symbol = NULL, limit = 100, filterSymbol = NULL, include = FALSE) +} +\arguments{ +\item{include}{} +} +\value{ + +} +\description{ +Get latest trades from all symbols up to 1 minute ago or get latest trades from a specific symbol without time limitation. Latest data is always returned in time descending order. +} +\examples{ +getTrades() +getTrades(filterSymbol = "BTC", limit = 25) +getTrades(symbol = "BITSTAMP_SPOT_BTC_USD", limit = 25) +} diff --git a/data-api/r-rest-2/man/setApiKey.Rd b/data-api/r-rest-2/man/setApiKey.Rd new file mode 100644 index 0000000000..ebad3e70f9 --- /dev/null +++ b/data-api/r-rest-2/man/setApiKey.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utils.R +\name{setApiKey} +\alias{setApiKey} +\title{Set your API Key} +\usage{ +setApiKey(apiKey) +} +\arguments{ +\item{apiKey}{} +} +\value{ + +} +\description{ +Set your API Key +} +\examples{ +setApiKey(XXXXXXXXXXXXXXXX) +} diff --git a/data-api/r-rest-2/tests/testthat.R b/data-api/r-rest-2/tests/testthat.R new file mode 100644 index 0000000000..a2b5c109e8 --- /dev/null +++ b/data-api/r-rest-2/tests/testthat.R @@ -0,0 +1,4 @@ +library(testthat) +library(rcoinapi) + +test_check("rcoinapi") diff --git a/data-api/r-rest-2/tests/testthat/test-listToStringArray.R b/data-api/r-rest-2/tests/testthat/test-listToStringArray.R new file mode 100644 index 0000000000..8849056e25 --- /dev/null +++ b/data-api/r-rest-2/tests/testthat/test-listToStringArray.R @@ -0,0 +1,3 @@ +test_that("multiplication works", { + expect_equal(2 * 2, 4) +}) diff --git a/data-api/r-rest/README.md b/data-api/r-rest/README.md new file mode 100644 index 0000000000..abb424c647 --- /dev/null +++ b/data-api/r-rest/README.md @@ -0,0 +1,47 @@ +Initialise +```{r} +library(httr) +library(jsonlite) +``` + +Setup GET request to coinapi +```{r} +base <- "https://rest.coinapi.io/" +endpoint <- "/v1/exchangerate/BTC?apikey=" # note the request is for aseets against BTC +api_key <- "[your key]" +``` + +Create query string +```{r} +call <- paste0(base, endpoint, api_key) +``` + +Retrieve data via GET call +```{r} +get_prices <- GET(call) +``` + +Returns class "response" +```{r} +class(get_prices) +``` + +Process into a data table +```{r} +get_prices_text <- content(get_prices, "text") # Convert to "character" +get_prices_json <- fromJSON(get_prices_text, flatten = TRUE) # Flatten into list +``` + +List contains two objects: + +1 - asset_id_base +2 - rates + +```{r} +names(get_prices_json) +``` + +```{r} +get_prices_json$asset_id_base +head(get_prices_json$rates) +``` diff --git a/data-api/r-rest/example.R b/data-api/r-rest/example.R new file mode 100644 index 0000000000..bc19cc89d2 --- /dev/null +++ b/data-api/r-rest/example.R @@ -0,0 +1,31 @@ +library(httr) +library(jsonlite) + +## I got a free account at coinapi.io +## Free account provides 100 daily requests free. +## The next tier allows 1000 daily requests for US$79/month + +base <- "https://rest.coinapi.io" +endpoint <- "/v1/exchangerate/BTC?apikey=" +api_key <- "[your key]" + +## Create +call <- paste0(base, endpoint, api_key) +# call +## Retrieve data via GET call +get_prices <- GET(call) + +## Returns class "response" +class(get_prices) + +## Process into a data table +get_prices_text <- content(get_prices, "text") # Convert to "character" +get_prices_json <- fromJSON(get_prices_text, flatten = TRUE) # Flatten into list + +## List contains two objects: +## 1 - asset_id_base +## 2 - rates + +rates <- get_prices_json$rates + +head(rates) diff --git a/ruby-rest/README.md b/data-api/ruby-rest/README.md similarity index 100% rename from ruby-rest/README.md rename to data-api/ruby-rest/README.md diff --git a/ruby-rest/coinapi_v1.rb b/data-api/ruby-rest/coinapi_v1.rb similarity index 95% rename from ruby-rest/coinapi_v1.rb rename to data-api/ruby-rest/coinapi_v1.rb index ddd0fa61c7..b926be716d 100644 --- a/ruby-rest/coinapi_v1.rb +++ b/data-api/ruby-rest/coinapi_v1.rb @@ -150,16 +150,6 @@ def orderbooks_historical_data(symbol_id:, time_start:, parameters: {}) end end - def twitter_latest_data(parameters: {}) - endpoint = "twitter/latest" - request(endpoint: endpoint, parameters: parameters) - end - - def twitter_historical_data(time_start:, parameters: {}) - endpoint = "twitter/history" - request(endpoint: endpoint, parameters: parameters) - end - private def default_headers headers = {} @@ -209,7 +199,7 @@ def request(endpoint:, parameters: {}) module Transformers class << self def asset(a) - if a[:type_is_crypto] == 0 + if a[:type_is_crypto] != 0 a[:type_is_crypto] = true else a[:type_is_crypto] = false diff --git a/ruby-rest/examples.rb b/data-api/ruby-rest/examples.rb similarity index 98% rename from ruby-rest/examples.rb rename to data-api/ruby-rest/examples.rb index 950420f8a8..07821628de 100644 --- a/ruby-rest/examples.rb +++ b/data-api/ruby-rest/examples.rb @@ -224,5 +224,4 @@ def print_entry(entry) print_entry(entry) end -twitter_latest_data = api.twitter_latest_data() -twitter_historical_data = api.twitter_historical_data(time_start: start_of_2016) + diff --git a/data-api/sandy-ws-v1.json b/data-api/sandy-ws-v1.json new file mode 100644 index 0000000000..3347569a25 --- /dev/null +++ b/data-api/sandy-ws-v1.json @@ -0,0 +1,124 @@ +{ + "[custom]-new-env-3": { + "url": "wss://ws-sandbox.coinapi.io/v1/", + "provider": "websocket", + "order": 1, + "methods": [ + { + "group": "Hello", + "methodName": "Trade-SPOT, COINBASE and ITBIT", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "trade" + ], + "subscribe_filter_symbol_id": [ + "BITSTAMP_SPOT_BTC_USD$", + "BITFINEX_SPOT_BTC_LTC$", + "COINBASE_", + "ITBIT_" + ] + } + } + }, + { + "group": "Hello", + "methodName": "Quotes-BTC and ETH", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "quote" + ], + "subscribe_filter_asset_id": [ + "BTC", + "ETH" + ] + } + } + }, + { + "group": "Hello", + "methodName": "All data types", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "trade", + "quote", + "book20" + ] + } + } + } + ] + }, + "[custom]-new-env-4": { + "url": "wss://ws.coinapi.io/v1/", + "provider": "websocket", + "order": 5, + "methods": [ + { + "group": "Hello", + "methodName": "Trade-SPOT, COINBASE and ITBIT", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "trade" + ], + "subscribe_filter_symbol_id": [ + "BITSTAMP_SPOT_BTC_USD$", + "BITFINEX_SPOT_BTC_LTC$", + "COINBASE_", + "ITBIT_" + ] + } + } + }, + { + "group": "Hello", + "methodName": "Quotes-BTC and ETH", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "quote" + ], + "subscribe_filter_asset_id": [ + "BTC", + "ETH" + ] + } + } + }, + { + "group": "Hello", + "methodName": "All data types", + "payload": { + "sample": { + "type": "hello", + "apikey": "73034021-THIS-IS-SAMPLE-KEY", + "heartbeat": false, + "subscribe_data_type": [ + "trade", + "quote", + "book20" + ] + } + } + } + ] + } +} \ No newline at end of file diff --git a/data-api/swift-rest/CoinAPI.swift b/data-api/swift-rest/CoinAPI.swift new file mode 100644 index 0000000000..84b0c50426 --- /dev/null +++ b/data-api/swift-rest/CoinAPI.swift @@ -0,0 +1,459 @@ +// +// CoinAPI.swift +// CoinAPIDemoSwift +// +// Created by Adrian Mayoral on 1/18/18. +// Copyright © 2018 Adrian Mayoral. All rights reserved. +// + +import Foundation + +/** BASE API URL **/ +fileprivate let COINAPI_URL = "https://rest.coinapi.io" +/** HEADER NAME **/ +fileprivate let HEADER_API_KEY = "X-CoinAPI-Key" + +/** Handler block **/ +typealias APIResponse = ((_ response: Any?, _ error: Error?) -> Void) + +/** Error Handler **/ +enum CoinAPIError: Error { + case invalidRequest + case invalidJSON + case unknown +} + +/** Metadata Functions **/ +protocol MetadataProtocol { + func metadataExchanges(completionHandler: @escaping APIResponse) + func metadataAssets(completionHandler: @escaping APIResponse) + func metadataSymbols(completionHandler: @escaping APIResponse) +} + +/** Exchange Rates Functions **/ +protocol ExchangeRatesProtocol { + func exchangeRatesBy(assetId base: String, idQuote: String, time: Int, completionHandler: @escaping APIResponse) + func allExchangeRatesBy(assetId base: String, completionHandler: @escaping APIResponse) +} + +/** Open, High, Low, Close Prices and Volume indicators Functions **/ +protocol OHLCVDataProtocol { + func allOHLCVPeriods(completionHandler: @escaping APIResponse) + func latestOHLCVData(symbol id: String, periodId: String, limit: Int, completionHandler: @escaping APIResponse) + func historialOHLCVData(symbol id: String, periodId: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) +} + +/** Trades Functions **/ +protocol TradesDataProtocol { + func latestTradesData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) + func historicalTradesData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) +} + +/** Quotes Functions **/ +protocol QuotesDataProtocol { + func currentQuotesData(symbol id: String, completionHandler: @escaping APIResponse) + func latestQuotesData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) + func historicalQuotesData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) +} + +/** Orderbooks Functions **/ +protocol OrderbooksDataProtocol { + func currentOrderBooksData(symbol id: String, completionHandler: @escaping APIResponse) + func latestOrderBooksData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) + func historicalOrderBooksData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) +} + +/* + * CoinAPI Class + **/ +class CoinAPI { + + private (set) var apiKey: String + + init(apiKey key: String) { + self.apiKey = key + } + + /* + * Perform URLRequest and return data based on the API response. + **/ + private func perform(request _request: URLRequest, completionHandler: @escaping APIResponse) { + let session = URLSession(configuration: .default) + let task = session.dataTask(with: _request) { (data: Data?, response: URLResponse?, error: Error?) in + + guard let responseData = data else { + completionHandler(nil, CoinAPIError.unknown) + return + } + + do { + let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .allowFragments) + completionHandler(jsonResponse, nil) + } catch { + completionHandler(nil, CoinAPIError.invalidJSON) + } + + } + + task.resume() + } +} + +// MARK: - Metadata Implementation +extension CoinAPI: MetadataProtocol { + + func metadataExchanges(completionHandler: @escaping APIResponse) { + guard let requestUrl = URL(string: COINAPI_URL.appending("/v1/exchanges")) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func metadataAssets(completionHandler: @escaping APIResponse) { + guard let requestUrl = URL(string: COINAPI_URL.appending("/v1/assets")) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func metadataSymbols(completionHandler: @escaping APIResponse) { + guard let requestUrl = URL(string: COINAPI_URL.appending("/v1/symbols")) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } +} + +// MARK: - Metadata Implementation +extension CoinAPI: ExchangeRatesProtocol { + + func exchangeRatesBy(assetId base: String, idQuote: String, time: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/exchangerate/\(base)/\(idQuote)" + if time > 0 { + requestResource = "/v1/exchangerate/\(base)/\(idQuote)?time=\(time)" + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func allExchangeRatesBy(assetId base: String, completionHandler: @escaping APIResponse) { + guard let requestUrl = URL(string: COINAPI_URL.appending("/v1/exchangerate/\(base)")) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } +} + +// MARK: - OHLCV Implementation +extension CoinAPI: OHLCVDataProtocol { + + func allOHLCVPeriods(completionHandler: @escaping APIResponse) { + guard let requestUrl = URL(string: COINAPI_URL.appending("/v1/ohlcv/periods")) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func latestOHLCVData(symbol id: String, periodId: String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/ohlcv/\(id)/latest?period_id=\(periodId)" + if limit > 0 { + requestResource = "/v1/ohlcv/\(id)/latest?period_id=\(periodId)&limit=\(limit)" + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func historialOHLCVData(symbol id: String, periodId: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/ohlcv/\(id)/latest?period_id=\(periodId)&time_start=\(timeStart)" + + if !timeEnd.isEmpty { + requestResource.append("&time_end=\(timeEnd)") + } + if limit > 0 { + requestResource.append("&limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } +} + +// MARK: - Trades Implementation +extension CoinAPI: TradesDataProtocol { + + func latestTradesData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/trades/latest" + + if !id.isEmpty { + requestResource.append("trades/\(id)/latest") + } + if limit > 0 { + requestResource.append("?limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func historicalTradesData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/trades/\(id)/history?time_start=\(timeStart)" + + if !timeEnd.isEmpty { + requestResource.append("&time_end=\(timeEnd)") + } + if limit > 0 { + requestResource.append("&limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } +} + +// MARK: - Quotes Implementation +extension CoinAPI: QuotesDataProtocol { + + func currentQuotesData(symbol id: String, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/quotes/current" + + if !id.isEmpty { + requestResource.append("/v1/quotes/\(id)/current") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func latestQuotesData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/quotes/latest" + + if !id.isEmpty { + requestResource = "/v1/quotes/\(id)/latest" + } + if limit > 0 { + requestResource.append("?limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func historicalQuotesData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/quotes/\(id)/history?time_start=\(timeStart)" + + if !timeEnd.isEmpty { + requestResource.append("&time_end=\(timeEnd)") + } + if limit > 0 { + requestResource.append("&limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + +} + +// MARK: - Order Books Implementation +extension CoinAPI: OrderbooksDataProtocol { + + func currentOrderBooksData(symbol id: String, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/orderbooks/current" + + if !id.isEmpty { + requestResource.append("/v1/orderbooks/\(id)/current") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func latestOrderBooksData(symbol id: String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/orderbooks/\(id)/latest" + + if limit > 0 { + requestResource.append("?limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + + func historicalOrderBooksData(symbol id: String, timeStart: String, timeEnd:String, limit: Int, completionHandler: @escaping APIResponse) { + // build URI string + var requestResource = "/v1/quotes/\(id)/history?time_start=\(timeStart)" + + if !timeEnd.isEmpty { + requestResource.append("&time_end=\(timeEnd)") + } + if limit > 0 { + requestResource.append("&limit=\(limit)") + } + + guard let requestUrl = URL(string: COINAPI_URL.appending(requestResource)) else { + completionHandler(nil, CoinAPIError.invalidRequest) + return + } + + // Build request + let request = NSMutableURLRequest(url: requestUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 100) + request.httpMethod = "GET" + request.addValue(self.apiKey, forHTTPHeaderField: HEADER_API_KEY) + + // Perform request + perform(request: request as URLRequest, completionHandler: completionHandler) + } + +} diff --git a/data-api/swift-rest/ViewController.swift b/data-api/swift-rest/ViewController.swift new file mode 100644 index 0000000000..9805ea1caf --- /dev/null +++ b/data-api/swift-rest/ViewController.swift @@ -0,0 +1,111 @@ +// +// ViewController.swift +// CoinAPIDemoSwift +// +// Created by Adrian Mayoral on 1/18/18. +// Copyright © 2018 Adrian Mayoral. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + let coin = CoinAPI(apiKey: "YOUR_API_KEY_HERE") + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + + coin.metadataExchanges { (jsonResponse: Any, error: Error?) in + print("Metadata - List all exchanges : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.metadataAssets { (jsonResponse: Any, error: Error?) in + print("Metadata - List all assets : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.metadataSymbols { (jsonResponse: Any, error: Error?) in + print("Metadata - List all symbols : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.exchangeRatesBy(assetId: "BTC", idQuote: "USD", time: 0) { (jsonResponse: Any, error: Error?) in + print("Exchange Rates - Get specific rate : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.allExchangeRatesBy(assetId: "BTC") { (jsonResponse: Any, error: Error?) in + print("Exchange Rates - Get all current rates : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.allOHLCVPeriods { (jsonResponse: Any, error: Error?) in + print("OHLCV - List all periods : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.latestOHLCVData(symbol: "BITSTAMP_SPOT_BTC_USD", periodId: "1MIN", limit: 0) { (jsonResponse: Any, error: Error?) in + print("OHLCV - Latest data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.historialOHLCVData(symbol: "BITSTAMP_SPOT_BTC_USD", periodId: "1MIN", timeStart: "2016-01-01T00:00:00", timeEnd: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("OHLCV - Historical data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.latestTradesData(symbol: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Trades - Latest data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.historicalTradesData(symbol: "BITSTAMP_SPOT_BTC_USD", timeStart: "2016-01-01T00:00:00", timeEnd: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Trades - Historical data :: \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.currentQuotesData(symbol: "") { (jsonResponse: Any, error: Error?) in + print("Quotes - Current data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.latestTradesData(symbol: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Quotes - Latest data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.historicalTradesData(symbol: "BITSTAMP_SPOT_BTC_USD", timeStart: "2016-01-01T00:00:00", timeEnd: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Quotes - Historical data :: \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.currentOrderBooksData(symbol: "") { (jsonResponse: Any, error: Error?) in + print("Orderbooks - Current data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.latestOrderBooksData(symbol: "BITSTAMP_SPOT_BTC_USD", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Orderbooks - Latest data : \(jsonResponse)") + print("error: \(String(describing: error))") + } + + coin.historicalOrderBooksData(symbol: "BITSTAMP_SPOT_BTC_USD", timeStart: "2016-01-01T00:00:00", timeEnd: "", limit: 0) { (jsonResponse: Any, error: Error?) in + print("Orderbooks - Historical data :: \(jsonResponse)") + print("error: \(String(describing: error))") + } + + } + +} + diff --git a/typescript-rest/coinapi_v1.ts b/data-api/typescript-rest/coinapi_v1.ts similarity index 87% rename from typescript-rest/coinapi_v1.ts rename to data-api/typescript-rest/coinapi_v1.ts index 9d1cedf437..cd1c3edc13 100644 --- a/typescript-rest/coinapi_v1.ts +++ b/data-api/typescript-rest/coinapi_v1.ts @@ -32,7 +32,7 @@ let transformResponse = (axios.defaults.transformResponse as AxiosTransformer[]) export default class COIN_API_SDK { private api_key = "" private headers = {} - private url = "https://rest-test.coinapi.io" + private url = "https://rest.coinapi.io" constructor(api_key: string = null) { if (api_key) { @@ -245,29 +245,6 @@ export default class COIN_API_SDK { return resp.data as Orderbook[] }) } - - twitter_latest_data(limit: number = null) { - let path = this.url + `/v1/twitter/latest` - let params: any = {} - if (limit) { params.limit = limit } - - return axios.get(path, { headers: this.headers, transformResponse, params }) - .then(resp => { - return resp.data as Tweet[] - }) - } - - twitter_historical_data(time_start: Date, time_end: Date = null, limit: number = null) { - let path = this.url + `/v1/twitter/history?time_start=${time_start.toISOString()}` - let params: any = {} - if (time_end) { params.time = time_end.toISOString() } - if (limit) { params.limit = limit } - - return axios.get(path, { headers: this.headers, transformResponse, params }) - .then(resp => { - return resp.data as Quote[] - }) - } } @@ -377,30 +354,3 @@ interface Orderbook { asks: Bid[] bids: Bid[] } - -interface Tweet { - createdAt: string - favoriteCount: number - favorited: boolean - filterLevel: string - iD: number - iDStr: string - inReplyToScreenName: string - inReplyToStatusID: number - inReplyToStatusIDStr: string - inReplyToUserID: number - inReplyToUserIDStr: string - lang: string - possiblySensitive: boolean - retweetCount: number - retweeted: boolean - source: string - text: string - fullText: string - truncated: boolean - withheldCopyright: boolean - withheldInCountries: string[] - withheldScope: string - quotedStatusID: number - quotedStatusIDStr: string -} diff --git a/typescript-rest/example_typescript.ts b/data-api/typescript-rest/example_typescript.ts similarity index 91% rename from typescript-rest/example_typescript.ts rename to data-api/typescript-rest/example_typescript.ts index 158dbac50f..540e1467a6 100644 --- a/typescript-rest/example_typescript.ts +++ b/data-api/typescript-rest/example_typescript.ts @@ -103,16 +103,6 @@ async function run(){ console.log('Orderbooks_historical_data:') console.log('number: ', Orderbooks_historical_data.length) Orderbooks_historical_data.forEach(x=> { console.log(x) }) - - let Twitter_latest_data = await sdk.twitter_latest_data(5) - console.log('Twitter_latest_data:') - console.log('number: ', Twitter_latest_data.length) - Twitter_latest_data.forEach(x=> { console.log(x) }) - - let Twitter_historical_data = await sdk.twitter_historical_data(t, new Date(), 5) - console.log('Twitter_historical_data:') - console.log('number: ', Twitter_historical_data.length) - Twitter_historical_data.forEach(x=> { console.log(x) }) } run(); \ No newline at end of file diff --git a/data-api/typescript-rest/package.json b/data-api/typescript-rest/package.json new file mode 100644 index 0000000000..8420818a81 --- /dev/null +++ b/data-api/typescript-rest/package.json @@ -0,0 +1,16 @@ +{ + "name": "typescript-rest", + "version": "1.0.0", + "description": "coinapi.io typescript sdk", + "main": "coinapi_v1.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "imRaziel", + "license": "MIT", + "dependencies": { + "@types/es6-promise": "0.0.32", + "axios": "^0.19.2" + }, + "repository": "https://github.com/coinapi/coinapi-sdk/tree/master/typescript-rest" +} diff --git a/typescript-rest/readme.md b/data-api/typescript-rest/readme.md similarity index 100% rename from typescript-rest/readme.md rename to data-api/typescript-rest/readme.md diff --git a/ems-cloud-mgmt-sdk/ada/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/ada/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/ada/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/ada/.openapi-generator/FILES new file mode 100644 index 0000000000..42af4d6daf --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/.openapi-generator/FILES @@ -0,0 +1,9 @@ +.openapi-generator-ignore +config.gpr +defaultpackage.gpr +src/-client.adb +src/.ads +src/client/-clients.adb +src/client/-clients.ads +src/model/-models.adb +src/model/-models.ads diff --git a/ems-cloud-mgmt-sdk/ada/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/ada/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/ada/config.gpr b/ems-cloud-mgmt-sdk/ada/config.gpr new file mode 100644 index 0000000000..e46b6311ef --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/config.gpr @@ -0,0 +1,83 @@ +abstract project Config is + for Source_Dirs use (); + + type Yes_No is ("yes", "no"); + + type Library_Type_Type is ("relocatable", "static", "static-pic"); + + type Build_Type is ("distrib", "debug", "optimize", "profile", "coverage"); + Mode : Build_Type := external ("BUILD", "debug"); + + Processors := External ("PROCESSORS", "1"); + + package Builder is + case Mode is + when "debug" => + for Default_Switches ("Ada") use ("-g", "-j" & Processors); + when others => + for Default_Switches ("Ada") use ("-g", "-O2", "-j" & Processors); + end case; + end Builder; + + package compiler is + warnings := ("-gnatwua"); + defaults := ("-gnat2012"); + case Mode is + when "distrib" => + for Default_Switches ("Ada") use defaults & ("-gnatafno", "-gnatVa", "-gnatwa"); + + when "debug" => + for Default_Switches ("Ada") use defaults & warnings + & ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM127"); + + when "coverage" => + for Default_Switches ("Ada") use defaults & warnings + & ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM127", + "-fprofile-arcs", "-ftest-coverage"); + + when "optimize" => + for Default_Switches ("Ada") use defaults & warnings + & ("-gnatn", "-gnatp", "-fdata-sections", "-ffunction-sections"); + + when "profile" => + for Default_Switches ("Ada") use defaults & warnings & ("-pg"); + + end case; + end compiler; + + package binder is + case Mode is + when "debug" => + for Default_Switches ("Ada") use ("-E"); + + when others => + for Default_Switches ("Ada") use ("-E"); + + end case; + end binder; + + package linker is + case Mode is + when "profile" => + for Default_Switches ("Ada") use ("-pg"); + + when "distrib" => + for Default_Switches ("Ada") use ("-s"); + + when "optimize" => + for Default_Switches ("Ada") use ("-Wl,--gc-sections"); + + when "coverage" => + for Default_Switches ("ada") use ("-fprofile-arcs"); + + when others => + null; + end case; + + end linker; + + package Ide is + for VCS_Kind use "git"; + end Ide; + +end Config; diff --git a/ems-cloud-mgmt-sdk/ada/defaultpackage.gpr b/ems-cloud-mgmt-sdk/ada/defaultpackage.gpr new file mode 100644 index 0000000000..8ae58ee0c5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/defaultpackage.gpr @@ -0,0 +1,26 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- The version of the OpenAPI document: 1.0.0 +-- +-- https://openapi-generator.tech +-- +-- NOTE: Auto generated by OpenAPI Generator (https://openapi-generator.tech). +with "config"; +with "utilada_sys"; +with "utilada_xml"; +with "utilada_http"; +with "security"; +with "swagger"; +project defaultPackage is + + Mains := ("-client.adb"); + for Main use Mains; + for Source_Dirs use ("src", "src/model", "src/client"); + for Object_Dir use "./" & Config'Exec_Dir & "/bin"; + + package Binder renames Config.Binder; + package Builder renames Config.Builder; + package Compiler renames Config.Compiler; + package Linker renames Config.Linker; + +end defaultPackage; diff --git a/ems-cloud-mgmt-sdk/ada/src/-client.adb b/ems-cloud-mgmt-sdk/ada/src/-client.adb new file mode 100644 index 0000000000..0540ce13f7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/-client.adb @@ -0,0 +1,43 @@ +with .Clients; +with .Models; +with Swagger; +with Util.Http.Clients.Curl; +with Ada.Text_IO; +with Ada.Command_Line; +with Ada.Calendar.Formatting; +with Ada.Exceptions; +procedure .Client is + + use Ada.Text_IO; + + procedure Usage; + + Server : constant Swagger.UString := Swagger.To_UString ("http://localhost:8080/v2"); + Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; + Arg : Positive := 1; + + procedure Usage is + begin + Put_Line ("Usage: defaultPackage {params}..."); + end Usage; + +begin + if Arg_Count <= 1 then + Usage; + return; + end if; + Util.Http.Clients.Curl.Register; + declare + Command : constant String := Ada.Command_Line.Argument (Arg); + Item : constant String := Ada.Command_Line.Argument (Arg + 1); + C : .Clients.Client_Type; + begin + C.Set_Server (Server); + Arg := Arg + 2; + + exception + when E : Constraint_Error => + Put_Line ("Constraint error raised: " & Ada.Exceptions.Exception_Message (E)); + + end; +end .Client; diff --git a/ems-cloud-mgmt-sdk/ada/src/.ads b/ems-cloud-mgmt-sdk/ada/src/.ads new file mode 100644 index 0000000000..1496881904 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/.ads @@ -0,0 +1,14 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- ------------ EDIT NOTE ------------ +-- This file was generated with openapi-generator. You can modify it to implement +-- the server. After you modify this file, you should add the following line +-- to the .openapi-generator-ignore file: +-- +-- src/.ads +-- +-- Then, you can drop this edit note comment. +-- ------------ EDIT NOTE ------------ +package is + +end ; diff --git a/ems-cloud-mgmt-sdk/ada/src/client/-clients.adb b/ems-cloud-mgmt-sdk/ada/src/client/-clients.adb new file mode 100644 index 0000000000..4298298eb1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/client/-clients.adb @@ -0,0 +1,146 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- +-- The version of the OpenAPI document: v1 +-- Contact: support@coinapi.io +-- +-- NOTE: This package is auto generated by OpenAPI-Generator 5.4.0. +-- https://openapi-generator.tech +-- Do not edit the class manually. + +pragma Warnings (Off, "*is not referenced"); +with Swagger.Streams; +package body .Clients is + pragma Style_Checks ("-mr"); + + -- Get balances + -- Get current currency balance from all or single exchange. + procedure V_1Balances_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.Balance_Type_Vectors.Vector) is + URI : Swagger.Clients.URI_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + + URI.Add_Param ("exchange_id", Exchange_Id); + URI.Set_Path ("/v1/balances"); + Client.Call (Swagger.Clients.GET, URI, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Balances_Get; + + -- Cancel all orders request + -- This request cancels all open orders on single specified exchange. + procedure V_1Orders_Cancel_All_Post + (Client : in out Client_Type; + Order_Cancel_All_Request_Type : in .Models.OrderCancelAllRequest_Type; + Result : out .Models.MessageReject_Type) is + URI : Swagger.Clients.URI_Type; + Req : Swagger.Clients.Request_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); + .Models.Serialize (Req.Stream, "", Order_Cancel_All_Request_Type); + + URI.Set_Path ("/v1/orders/cancel/all"); + Client.Call (Swagger.Clients.POST, URI, Req, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Orders_Cancel_All_Post; + + -- Cancel order request + -- Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + procedure V_1Orders_Cancel_Post + (Client : in out Client_Type; + Order_Cancel_Single_Request_Type : in .Models.OrderCancelSingleRequest_Type; + Result : out .Models.OrderExecutionReport_Type) is + URI : Swagger.Clients.URI_Type; + Req : Swagger.Clients.Request_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); + .Models.Serialize (Req.Stream, "", Order_Cancel_Single_Request_Type); + + URI.Set_Path ("/v1/orders/cancel"); + Client.Call (Swagger.Clients.POST, URI, Req, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Orders_Cancel_Post; + + -- Get open orders + -- Get last execution reports for open orders across all or single exchange. + procedure V_1Orders_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.OrderExecutionReport_Type_Vectors.Vector) is + URI : Swagger.Clients.URI_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + + URI.Add_Param ("exchange_id", Exchange_Id); + URI.Set_Path ("/v1/orders"); + Client.Call (Swagger.Clients.GET, URI, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Orders_Get; + + -- Send new order + -- This request creating new order for the specific exchange. + procedure V_1Orders_Post + (Client : in out Client_Type; + Order_New_Single_Request_Type : in .Models.OrderNewSingleRequest_Type; + Result : out .Models.OrderExecutionReport_Type) is + URI : Swagger.Clients.URI_Type; + Req : Swagger.Clients.Request_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + Client.Initialize (Req, (1 => Swagger.Clients.APPLICATION_JSON)); + .Models.Serialize (Req.Stream, "", Order_New_Single_Request_Type); + + URI.Set_Path ("/v1/orders"); + Client.Call (Swagger.Clients.POST, URI, Req, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Orders_Post; + + -- Get order execution report + -- Get the last order execution report for the specified order. The requested order does not need to be active or opened. + procedure V_1Orders_Status_Client_Order_Id_Get + (Client : in out Client_Type; + Client_Order_Id : in Swagger.UString; + Result : out .Models.OrderExecutionReport_Type) is + URI : Swagger.Clients.URI_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((1 => Swagger.Clients.APPLICATION_JSON)); + + URI.Set_Path ("/v1/orders/status/{client_order_id}"); + URI.Set_Path_Param ("client_order_id", Client_Order_Id); + Client.Call (Swagger.Clients.GET, URI, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Orders_Status_Client_Order_Id_Get; + + -- Get open positions + -- Get current open positions across all or single exchange. + procedure V_1Positions_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.Position_Type_Vectors.Vector) is + URI : Swagger.Clients.URI_Type; + Reply : Swagger.Value_Type; + begin + Client.Set_Accept ((Swagger.Clients.APPLICATION_JSON, + Swagger.Clients.APPLICTION_JSON)); + + URI.Add_Param ("exchange_id", Exchange_Id); + URI.Set_Path ("/v1/positions"); + Client.Call (Swagger.Clients.GET, URI, Reply); + .Models.Deserialize (Reply, "", Result); + end V_1Positions_Get; +end .Clients; diff --git a/ems-cloud-mgmt-sdk/ada/src/client/-clients.ads b/ems-cloud-mgmt-sdk/ada/src/client/-clients.ads new file mode 100644 index 0000000000..98bc0aba15 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/client/-clients.ads @@ -0,0 +1,67 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- +-- The version of the OpenAPI document: v1 +-- Contact: support@coinapi.io +-- +-- NOTE: This package is auto generated by OpenAPI-Generator 5.4.0. +-- https://openapi-generator.tech +-- Do not edit the class manually. + +with .Models; +with Swagger.Clients; +package .Clients is + pragma Style_Checks ("-mr"); + + type Client_Type is new Swagger.Clients.Client_Type with null record; + + -- Get balances + -- Get current currency balance from all or single exchange. + procedure V_1Balances_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.Balance_Type_Vectors.Vector); + + -- Cancel all orders request + -- This request cancels all open orders on single specified exchange. + procedure V_1Orders_Cancel_All_Post + (Client : in out Client_Type; + Order_Cancel_All_Request_Type : in .Models.OrderCancelAllRequest_Type; + Result : out .Models.MessageReject_Type); + + -- Cancel order request + -- Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + procedure V_1Orders_Cancel_Post + (Client : in out Client_Type; + Order_Cancel_Single_Request_Type : in .Models.OrderCancelSingleRequest_Type; + Result : out .Models.OrderExecutionReport_Type); + + -- Get open orders + -- Get last execution reports for open orders across all or single exchange. + procedure V_1Orders_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.OrderExecutionReport_Type_Vectors.Vector); + + -- Send new order + -- This request creating new order for the specific exchange. + procedure V_1Orders_Post + (Client : in out Client_Type; + Order_New_Single_Request_Type : in .Models.OrderNewSingleRequest_Type; + Result : out .Models.OrderExecutionReport_Type); + + -- Get order execution report + -- Get the last order execution report for the specified order. The requested order does not need to be active or opened. + procedure V_1Orders_Status_Client_Order_Id_Get + (Client : in out Client_Type; + Client_Order_Id : in Swagger.UString; + Result : out .Models.OrderExecutionReport_Type); + + -- Get open positions + -- Get current open positions across all or single exchange. + procedure V_1Positions_Get + (Client : in out Client_Type; + Exchange_Id : in Swagger.Nullable_UString; + Result : out .Models.Position_Type_Vectors.Vector); + +end .Clients; diff --git a/ems-cloud-mgmt-sdk/ada/src/model/-models.adb b/ems-cloud-mgmt-sdk/ada/src/model/-models.adb new file mode 100644 index 0000000000..8d57dc9f19 --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/model/-models.adb @@ -0,0 +1,926 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- +-- The version of the OpenAPI document: v1 +-- Contact: support@coinapi.io +-- +-- NOTE: This package is auto generated by OpenAPI-Generator 5.4.0. +-- https://openapi-generator.tech +-- Do not edit the class manually. + + +package body .Models is + pragma Style_Checks ("-mr"); + + pragma Warnings (Off, "*use clause for package*"); + + use Swagger.Streams; + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in RejectReason_Type) is + begin + Into.Start_Entity (Name); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in RejectReason_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out RejectReason_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out RejectReason_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : RejectReason_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in MessageReject_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("type", Value.P_Type); + Serialize (Into, "reject_reason", Value.Reject_Reason); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Into.Write_Entity ("message", Value.Message); + Into.Write_Entity ("rejected_message", Value.Rejected_Message); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in MessageReject_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out MessageReject_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "type", Value.P_Type); + Deserialize (Object, "reject_reason", Value.Reject_Reason); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Swagger.Streams.Deserialize (Object, "message", Value.Message); + Swagger.Streams.Deserialize (Object, "rejected_message", Value.Rejected_Message); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out MessageReject_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : MessageReject_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in ValidationError_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("type", Value.P_Type); + Into.Write_Entity ("title", Value.Title); + Serialize (Into, "status", Value.Status); + Into.Write_Entity ("traceId", Value.Trace_Id); + Into.Write_Entity ("errors", Value.Errors); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in ValidationError_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out ValidationError_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "type", Value.P_Type); + Swagger.Streams.Deserialize (Object, "title", Value.Title); + Swagger.Streams.Deserialize (Object, "status", Value.Status); + Swagger.Streams.Deserialize (Object, "traceId", Value.Trace_Id); + Swagger.Streams.Deserialize (Object, "errors", Value.Errors); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out ValidationError_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : ValidationError_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdType_Type) is + begin + Into.Start_Entity (Name); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdType_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdType_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdType_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrdType_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdStatus_Type) is + begin + Into.Start_Entity (Name); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdStatus_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdStatus_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdStatus_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrdStatus_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelAllRequest_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelAllRequest_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelAllRequest_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelAllRequest_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrderCancelAllRequest_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelSingleRequest_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Into.Write_Entity ("exchange_order_id", Value.Exchange_Order_Id); + Into.Write_Entity ("client_order_id", Value.Client_Order_Id); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelSingleRequest_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelSingleRequest_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Swagger.Streams.Deserialize (Object, "exchange_order_id", Value.Exchange_Order_Id); + Swagger.Streams.Deserialize (Object, "client_order_id", Value.Client_Order_Id); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelSingleRequest_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrderCancelSingleRequest_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdSide_Type) is + begin + Into.Start_Entity (Name); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdSide_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdSide_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdSide_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrdSide_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in TimeInForce_Type) is + begin + Into.Start_Entity (Name); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in TimeInForce_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out TimeInForce_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out TimeInForce_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : TimeInForce_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderNewSingleRequest_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Into.Write_Entity ("client_order_id", Value.Client_Order_Id); + Into.Write_Entity ("symbol_id_exchange", Value.Symbol_Id_Exchange); + Into.Write_Entity ("symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Serialize (Into, "amount_order", Value.Amount_Order); + Serialize (Into, "price", Value.Price); + Serialize (Into, "side", Value.Side); + Serialize (Into, "order_type", Value.Order_Type); + Serialize (Into, "time_in_force", Value.Time_In_Force); + Serialize (Into, "expire_time", Value.Expire_Time); + Serialize (Into, "exec_inst", Value.Exec_Inst); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderNewSingleRequest_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderNewSingleRequest_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Swagger.Streams.Deserialize (Object, "client_order_id", Value.Client_Order_Id); + Swagger.Streams.Deserialize (Object, "symbol_id_exchange", Value.Symbol_Id_Exchange); + Swagger.Streams.Deserialize (Object, "symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Swagger.Streams.Deserialize (Object, "amount_order", Value.Amount_Order); + Swagger.Streams.Deserialize (Object, "price", Value.Price); + Deserialize (Object, "side", Value.Side); + Deserialize (Object, "order_type", Value.Order_Type); + Deserialize (Object, "time_in_force", Value.Time_In_Force); + Swagger.Streams.Deserialize (Object, "expire_time", Value.Expire_Time); + Swagger.Streams.Deserialize (Object, "exec_inst", Value.Exec_Inst); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderNewSingleRequest_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrderNewSingleRequest_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Fills_Type) is + begin + Into.Start_Entity (Name); + Serialize (Into, "time", Value.Time); + Serialize (Into, "price", Value.Price); + Serialize (Into, "amount", Value.Amount); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Fills_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Fills_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "time", Value.Time); + Swagger.Streams.Deserialize (Object, "price", Value.Price); + Swagger.Streams.Deserialize (Object, "amount", Value.Amount); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Fills_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : Fills_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReport_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Into.Write_Entity ("client_order_id", Value.Client_Order_Id); + Into.Write_Entity ("symbol_id_exchange", Value.Symbol_Id_Exchange); + Into.Write_Entity ("symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Serialize (Into, "amount_order", Value.Amount_Order); + Serialize (Into, "price", Value.Price); + Serialize (Into, "side", Value.Side); + Serialize (Into, "order_type", Value.Order_Type); + Serialize (Into, "time_in_force", Value.Time_In_Force); + Serialize (Into, "expire_time", Value.Expire_Time); + Serialize (Into, "exec_inst", Value.Exec_Inst); + Into.Write_Entity ("client_order_id_format_exchange", Value.Client_Order_Id_Format_Exchange); + Into.Write_Entity ("exchange_order_id", Value.Exchange_Order_Id); + Serialize (Into, "amount_open", Value.Amount_Open); + Serialize (Into, "amount_filled", Value.Amount_Filled); + Serialize (Into, "avg_px", Value.Avg_Px); + Serialize (Into, "status", Value.Status); + Serialize (Into, "status_history", Value.Status_History); + Into.Write_Entity ("error_message", Value.Error_Message); + Serialize (Into, "fills", Value.Fills); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReport_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReport_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Swagger.Streams.Deserialize (Object, "client_order_id", Value.Client_Order_Id); + Swagger.Streams.Deserialize (Object, "symbol_id_exchange", Value.Symbol_Id_Exchange); + Swagger.Streams.Deserialize (Object, "symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Swagger.Streams.Deserialize (Object, "amount_order", Value.Amount_Order); + Swagger.Streams.Deserialize (Object, "price", Value.Price); + Deserialize (Object, "side", Value.Side); + Deserialize (Object, "order_type", Value.Order_Type); + Deserialize (Object, "time_in_force", Value.Time_In_Force); + Swagger.Streams.Deserialize (Object, "expire_time", Value.Expire_Time); + Swagger.Streams.Deserialize (Object, "exec_inst", Value.Exec_Inst); + Swagger.Streams.Deserialize (Object, "client_order_id_format_exchange", Value.Client_Order_Id_Format_Exchange); + Swagger.Streams.Deserialize (Object, "exchange_order_id", Value.Exchange_Order_Id); + Swagger.Streams.Deserialize (Object, "amount_open", Value.Amount_Open); + Swagger.Streams.Deserialize (Object, "amount_filled", Value.Amount_Filled); + Swagger.Streams.Deserialize (Object, "avg_px", Value.Avg_Px); + Deserialize (Object, "status", Value.Status); + Swagger.Streams.Deserialize (Object, "status_history", Value.Status_History); + Swagger.Streams.Deserialize (Object, "error_message", Value.Error_Message); + Deserialize (Object, "fills", Value.Fills); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReport_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrderExecutionReport_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReportAllOf_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("client_order_id_format_exchange", Value.Client_Order_Id_Format_Exchange); + Into.Write_Entity ("exchange_order_id", Value.Exchange_Order_Id); + Serialize (Into, "amount_open", Value.Amount_Open); + Serialize (Into, "amount_filled", Value.Amount_Filled); + Serialize (Into, "avg_px", Value.Avg_Px); + Serialize (Into, "status", Value.Status); + Serialize (Into, "status_history", Value.Status_History); + Into.Write_Entity ("error_message", Value.Error_Message); + Serialize (Into, "fills", Value.Fills); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReportAllOf_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReportAllOf_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "client_order_id_format_exchange", Value.Client_Order_Id_Format_Exchange); + Swagger.Streams.Deserialize (Object, "exchange_order_id", Value.Exchange_Order_Id); + Swagger.Streams.Deserialize (Object, "amount_open", Value.Amount_Open); + Swagger.Streams.Deserialize (Object, "amount_filled", Value.Amount_Filled); + Swagger.Streams.Deserialize (Object, "avg_px", Value.Avg_Px); + Deserialize (Object, "status", Value.Status); + Swagger.Streams.Deserialize (Object, "status_history", Value.Status_History); + Swagger.Streams.Deserialize (Object, "error_message", Value.Error_Message); + Deserialize (Object, "fills", Value.Fills); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReportAllOf_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : OrderExecutionReportAllOf_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in BalanceData_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("asset_id_exchange", Value.Asset_Id_Exchange); + Into.Write_Entity ("asset_id_coinapi", Value.Asset_Id_Coinapi); + Serialize (Into, "balance", Value.Balance); + Serialize (Into, "available", Value.Available); + Serialize (Into, "locked", Value.Locked); + Into.Write_Entity ("last_updated_by", Value.Last_Updated_By); + Serialize (Into, "rate_usd", Value.Rate_Usd); + Serialize (Into, "traded", Value.Traded); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in BalanceData_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out BalanceData_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "asset_id_exchange", Value.Asset_Id_Exchange); + Swagger.Streams.Deserialize (Object, "asset_id_coinapi", Value.Asset_Id_Coinapi); + Swagger.Streams.Deserialize (Object, "balance", Value.Balance); + Swagger.Streams.Deserialize (Object, "available", Value.Available); + Swagger.Streams.Deserialize (Object, "locked", Value.Locked); + Swagger.Streams.Deserialize (Object, "last_updated_by", Value.Last_Updated_By); + Swagger.Streams.Deserialize (Object, "rate_usd", Value.Rate_Usd); + Swagger.Streams.Deserialize (Object, "traded", Value.Traded); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out BalanceData_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : BalanceData_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Balance_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Serialize (Into, "data", Value.Data); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Balance_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Balance_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Deserialize (Object, "data", Value.Data); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Balance_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : Balance_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Position_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("exchange_id", Value.Exchange_Id); + Serialize (Into, "data", Value.Data); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Position_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Position_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "exchange_id", Value.Exchange_Id); + Deserialize (Object, "data", Value.Data); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Position_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : Position_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in PositionData_Type) is + begin + Into.Start_Entity (Name); + Into.Write_Entity ("symbol_id_exchange", Value.Symbol_Id_Exchange); + Into.Write_Entity ("symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Serialize (Into, "avg_entry_price", Value.Avg_Entry_Price); + Serialize (Into, "quantity", Value.Quantity); + Serialize (Into, "side", Value.Side); + Serialize (Into, "unrealized_pnl", Value.Unrealized_Pnl); + Serialize (Into, "leverage", Value.Leverage); + Into.Write_Entity ("cross_margin", Value.Cross_Margin); + Serialize (Into, "liquidation_price", Value.Liquidation_Price); + Into.Write_Entity ("raw_data", Value.Raw_Data); + Into.End_Entity (Name); + end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in PositionData_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out PositionData_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Swagger.Streams.Deserialize (Object, "symbol_id_exchange", Value.Symbol_Id_Exchange); + Swagger.Streams.Deserialize (Object, "symbol_id_coinapi", Value.Symbol_Id_Coinapi); + Swagger.Streams.Deserialize (Object, "avg_entry_price", Value.Avg_Entry_Price); + Swagger.Streams.Deserialize (Object, "quantity", Value.Quantity); + Deserialize (Object, "side", Value.Side); + Swagger.Streams.Deserialize (Object, "unrealized_pnl", Value.Unrealized_Pnl); + Swagger.Streams.Deserialize (Object, "leverage", Value.Leverage); + Swagger.Streams.Deserialize (Object, "cross_margin", Value.Cross_Margin); + Swagger.Streams.Deserialize (Object, "liquidation_price", Value.Liquidation_Price); + Deserialize (Object, "raw_data", Value.Raw_Data); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out PositionData_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : PositionData_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + + + +end .Models; diff --git a/ems-cloud-mgmt-sdk/ada/src/model/-models.ads b/ems-cloud-mgmt-sdk/ada/src/model/-models.ads new file mode 100644 index 0000000000..eba98727ec --- /dev/null +++ b/ems-cloud-mgmt-sdk/ada/src/model/-models.ads @@ -0,0 +1,561 @@ +-- EMS _ REST API +-- This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems_gateway_aws_eu_central_1_dev.coinapi.io/
Self Hosted Production IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems_gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self_Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X_CoinAPI_Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X_CoinAPI_Key` and API key as its value. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY`, then the authorization header you should send to us will look like:

`X_CoinAPI_Key: 73034021_THIS_IS_SAMPLE_KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021_THIS_IS_SAMPLE_KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021_THIS_IS_SAMPLE_KEY` +-- +-- The version of the OpenAPI document: v1 +-- Contact: support@coinapi.io +-- +-- NOTE: This package is auto generated by OpenAPI-Generator 5.4.0. +-- https://openapi-generator.tech +-- Do not edit the class manually. + +with Swagger.Streams; +with Ada.Containers.Vectors; +package .Models is + pragma Style_Checks ("-mr"); + + + + type RejectReason_Type is + record + end record; + + package RejectReason_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => RejectReason_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in RejectReason_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in RejectReason_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out RejectReason_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out RejectReason_Type_Vectors.Vector); + + + + -- ------------------------------ + -- MessageReject object. + -- ------------------------------ + type MessageReject_Type is + record + P_Type : Swagger.Nullable_UString; + Reject_Reason : .Models.RejectReason_Type; + Exchange_Id : Swagger.Nullable_UString; + Message : Swagger.Nullable_UString; + Rejected_Message : Swagger.Nullable_UString; + end record; + + package MessageReject_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => MessageReject_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in MessageReject_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in MessageReject_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out MessageReject_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out MessageReject_Type_Vectors.Vector); + + + + -- ------------------------------ + -- JSON validation error. + -- ------------------------------ + type ValidationError_Type is + record + P_Type : Swagger.Nullable_UString; + Title : Swagger.Nullable_UString; + Status : Swagger.Number; + Trace_Id : Swagger.Nullable_UString; + Errors : Swagger.Nullable_UString; + end record; + + package ValidationError_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => ValidationError_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in ValidationError_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in ValidationError_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out ValidationError_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out ValidationError_Type_Vectors.Vector); + + + + + type OrdType_Type is + record + end record; + + package OrdType_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrdType_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdType_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdType_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdType_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdType_Type_Vectors.Vector); + + + + + type OrdStatus_Type is + record + end record; + + package OrdStatus_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrdStatus_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdStatus_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdStatus_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdStatus_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdStatus_Type_Vectors.Vector); + + + + + type OrderCancelAllRequest_Type is + record + Exchange_Id : Swagger.UString; + end record; + + package OrderCancelAllRequest_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrderCancelAllRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelAllRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelAllRequest_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelAllRequest_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelAllRequest_Type_Vectors.Vector); + + + + + type OrderCancelSingleRequest_Type is + record + Exchange_Id : Swagger.UString; + Exchange_Order_Id : Swagger.Nullable_UString; + Client_Order_Id : Swagger.Nullable_UString; + end record; + + package OrderCancelSingleRequest_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrderCancelSingleRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelSingleRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderCancelSingleRequest_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelSingleRequest_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderCancelSingleRequest_Type_Vectors.Vector); + + + + + type OrdSide_Type is + record + end record; + + package OrdSide_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrdSide_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdSide_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrdSide_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdSide_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrdSide_Type_Vectors.Vector); + + + + + type TimeInForce_Type is + record + end record; + + package TimeInForce_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => TimeInForce_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in TimeInForce_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in TimeInForce_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out TimeInForce_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out TimeInForce_Type_Vectors.Vector); + + + + + type OrderNewSingleRequest_Type is + record + Exchange_Id : Swagger.UString; + Client_Order_Id : Swagger.UString; + Symbol_Id_Exchange : Swagger.Nullable_UString; + Symbol_Id_Coinapi : Swagger.Nullable_UString; + Amount_Order : Swagger.Number; + Price : Swagger.Number; + Side : .Models.OrdSide_Type; + Order_Type : .Models.OrdType_Type; + Time_In_Force : .Models.TimeInForce_Type; + Expire_Time : Swagger.Nullable_Date; + Exec_Inst : Swagger.UString_Vectors.Vector; + end record; + + package OrderNewSingleRequest_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrderNewSingleRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderNewSingleRequest_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderNewSingleRequest_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderNewSingleRequest_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderNewSingleRequest_Type_Vectors.Vector); + + + + -- ------------------------------ + -- Relay fill information on working orders. + -- ------------------------------ + type Fills_Type is + record + Time : Swagger.Nullable_Date; + Price : Swagger.Number; + Amount : Swagger.Number; + end record; + + package Fills_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => Fills_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Fills_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Fills_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Fills_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Fills_Type_Vectors.Vector); + + + + + type OrderExecutionReport_Type is + record + Exchange_Id : Swagger.UString; + Client_Order_Id : Swagger.UString; + Symbol_Id_Exchange : Swagger.Nullable_UString; + Symbol_Id_Coinapi : Swagger.Nullable_UString; + Amount_Order : Swagger.Number; + Price : Swagger.Number; + Side : .Models.OrdSide_Type; + Order_Type : .Models.OrdType_Type; + Time_In_Force : .Models.TimeInForce_Type; + Expire_Time : Swagger.Nullable_Date; + Exec_Inst : Swagger.UString_Vectors.Vector; + Client_Order_Id_Format_Exchange : Swagger.UString; + Exchange_Order_Id : Swagger.Nullable_UString; + Amount_Open : Swagger.Number; + Amount_Filled : Swagger.Number; + Avg_Px : Swagger.Number; + Status : .Models.OrdStatus_Type; + Status_History : Swagger.UString_Vectors.Vector_Vectors.Vector; + Error_Message : Swagger.Nullable_UString; + Fills : .Models.Fills_Type_Vectors.Vector; + end record; + + package OrderExecutionReport_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrderExecutionReport_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReport_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReport_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReport_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReport_Type_Vectors.Vector); + + + + + type OrderExecutionReportAllOf_Type is + record + Client_Order_Id_Format_Exchange : Swagger.UString; + Exchange_Order_Id : Swagger.Nullable_UString; + Amount_Open : Swagger.Number; + Amount_Filled : Swagger.Number; + Avg_Px : Swagger.Number; + Status : .Models.OrdStatus_Type; + Status_History : Swagger.UString_Vectors.Vector_Vectors.Vector; + Error_Message : Swagger.Nullable_UString; + Fills : .Models.Fills_Type_Vectors.Vector; + end record; + + package OrderExecutionReportAllOf_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => OrderExecutionReportAllOf_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReportAllOf_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in OrderExecutionReportAllOf_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReportAllOf_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out OrderExecutionReportAllOf_Type_Vectors.Vector); + + + + + type BalanceData_Type is + record + Asset_Id_Exchange : Swagger.Nullable_UString; + Asset_Id_Coinapi : Swagger.Nullable_UString; + Balance : double; + Available : double; + Locked : double; + Last_Updated_By : Swagger.Nullable_UString; + Rate_Usd : double; + Traded : double; + end record; + + package BalanceData_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => BalanceData_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in BalanceData_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in BalanceData_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out BalanceData_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out BalanceData_Type_Vectors.Vector); + + + + + type Balance_Type is + record + Exchange_Id : Swagger.Nullable_UString; + Data : .Models.BalanceData_Type_Vectors.Vector; + end record; + + package Balance_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => Balance_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Balance_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Balance_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Balance_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Balance_Type_Vectors.Vector); + + + + + type Position_Type is + record + Exchange_Id : Swagger.Nullable_UString; + Data : .Models.PositionData_Type_Vectors.Vector; + end record; + + package Position_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => Position_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Position_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Position_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Position_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Position_Type_Vectors.Vector); + + + + + type PositionData_Type is + record + Symbol_Id_Exchange : Swagger.Nullable_UString; + Symbol_Id_Coinapi : Swagger.Nullable_UString; + Avg_Entry_Price : Swagger.Number; + Quantity : Swagger.Number; + Side : .Models.OrdSide_Type; + Unrealized_Pnl : Swagger.Number; + Leverage : Swagger.Number; + Cross_Margin : Swagger.Nullable_Boolean; + Liquidation_Price : Swagger.Number; + Raw_Data : Swagger.Object; + end record; + + package PositionData_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => PositionData_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in PositionData_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in PositionData_Type_Vectors.Vector); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out PositionData_Type); + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out PositionData_Type_Vectors.Vector); + + + +end .Models; diff --git a/ems-cloud-mgmt-sdk/android/.gitignore b/ems-cloud-mgmt-sdk/android/.gitignore new file mode 100644 index 0000000000..a836875126 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/.gitignore @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks diff --git a/ems-cloud-mgmt-sdk/android/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/android/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/android/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/android/.openapi-generator/FILES new file mode 100644 index 0000000000..ec7deaeb08 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/.openapi-generator/FILES @@ -0,0 +1,63 @@ +.gitignore +.openapi-generator-ignore +README.md +build.gradle +docs/Balance.md +docs/BalanceData.md +docs/BalancesApi.md +docs/Fills.md +docs/MessageReject.md +docs/OrdSide.md +docs/OrdStatus.md +docs/OrdType.md +docs/OrderCancelAllRequest.md +docs/OrderCancelSingleRequest.md +docs/OrderExecutionReport.md +docs/OrderExecutionReportAllOf.md +docs/OrderNewSingleRequest.md +docs/OrdersApi.md +docs/Position.md +docs/PositionData.md +docs/PositionsApi.md +docs/RejectReason.md +docs/TimeInForce.md +docs/ValidationError.md +git_push.sh +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiInvoker.java +src/main/java/org/openapitools/client/JsonUtil.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/api/BalancesApi.java +src/main/java/org/openapitools/client/api/OrdersApi.java +src/main/java/org/openapitools/client/api/PositionsApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/model/Balance.java +src/main/java/org/openapitools/client/model/BalanceData.java +src/main/java/org/openapitools/client/model/Fills.java +src/main/java/org/openapitools/client/model/MessageReject.java +src/main/java/org/openapitools/client/model/OrdSide.java +src/main/java/org/openapitools/client/model/OrdStatus.java +src/main/java/org/openapitools/client/model/OrdType.java +src/main/java/org/openapitools/client/model/OrderCancelAllRequest.java +src/main/java/org/openapitools/client/model/OrderCancelSingleRequest.java +src/main/java/org/openapitools/client/model/OrderExecutionReport.java +src/main/java/org/openapitools/client/model/OrderExecutionReportAllOf.java +src/main/java/org/openapitools/client/model/OrderNewSingleRequest.java +src/main/java/org/openapitools/client/model/Position.java +src/main/java/org/openapitools/client/model/PositionData.java +src/main/java/org/openapitools/client/model/RejectReason.java +src/main/java/org/openapitools/client/model/TimeInForce.java +src/main/java/org/openapitools/client/model/ValidationError.java +src/main/java/org/openapitools/client/request/DeleteRequest.java +src/main/java/org/openapitools/client/request/GetRequest.java +src/main/java/org/openapitools/client/request/PatchRequest.java +src/main/java/org/openapitools/client/request/PostRequest.java +src/main/java/org/openapitools/client/request/PutRequest.java diff --git a/ems-cloud-mgmt-sdk/android/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/android/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/android/README.md b/ems-cloud-mgmt-sdk/android/README.md new file mode 100644 index 0000000000..97dfff88e0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/README.md @@ -0,0 +1,128 @@ +# openapi-android-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + openapi-android-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:openapi-android-client:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +- target/openapi-android-client-1.0.0.jar +- target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.api.BalancesApi; + +public class BalancesApiExample { + + public static void main(String[] args) { + BalancesApi apiInstance = new BalancesApi(); + String exchangeId = KRAKEN; // String | Filter the balances to the specific exchange. + try { + List result = apiInstance.v1BalancesGet(exchangeId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BalancesApi#v1BalancesGet"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*BalancesApi* | [**v1BalancesGet**](docs/BalancesApi.md#v1BalancesGet) | **GET** /v1/balances | Get balances +*OrdersApi* | [**v1OrdersCancelAllPost**](docs/OrdersApi.md#v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +*OrdersApi* | [**v1OrdersCancelPost**](docs/OrdersApi.md#v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +*OrdersApi* | [**v1OrdersGet**](docs/OrdersApi.md#v1OrdersGet) | **GET** /v1/orders | Get open orders +*OrdersApi* | [**v1OrdersPost**](docs/OrdersApi.md#v1OrdersPost) | **POST** /v1/orders | Send new order +*OrdersApi* | [**v1OrdersStatusClientOrderIdGet**](docs/OrdersApi.md#v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report +*PositionsApi* | [**v1PositionsGet**](docs/PositionsApi.md#v1PositionsGet) | **GET** /v1/positions | Get open positions + + +## Documentation for Models + + - [Balance](docs/Balance.md) + - [BalanceData](docs/BalanceData.md) + - [Fills](docs/Fills.md) + - [MessageReject](docs/MessageReject.md) + - [OrdSide](docs/OrdSide.md) + - [OrdStatus](docs/OrdStatus.md) + - [OrdType](docs/OrdType.md) + - [OrderCancelAllRequest](docs/OrderCancelAllRequest.md) + - [OrderCancelSingleRequest](docs/OrderCancelSingleRequest.md) + - [OrderExecutionReport](docs/OrderExecutionReport.md) + - [OrderExecutionReportAllOf](docs/OrderExecutionReportAllOf.md) + - [OrderNewSingleRequest](docs/OrderNewSingleRequest.md) + - [Position](docs/Position.md) + - [PositionData](docs/PositionData.md) + - [RejectReason](docs/RejectReason.md) + - [TimeInForce](docs/TimeInForce.md) + - [ValidationError](docs/ValidationError.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. +Authentication schemes defined for the API: + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +support@coinapi.io + diff --git a/ems-cloud-mgmt-sdk/android/build.gradle b/ems-cloud-mgmt-sdk/android/build.gradle new file mode 100644 index 0000000000..afa1d97884 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/build.gradle @@ -0,0 +1,98 @@ +group = 'org.openapitools' +project.version = '1.0.0' + +buildscript { + repositories { + mavenLocal() + google() + maven { + url 'https://dl.google.com/dl/android/maven2' + } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.2.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + + +apply plugin: 'com.android.library' +apply plugin: 'com.github.dcendents.android-maven' + +android { + compileSdkVersion 25 + buildToolsVersion '28.0.3' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + lintOptions { + abortOnError false + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.all { output -> + if (outputFile != null && outputFileName.endsWith('.aar')) { + outputFileName = "${archivesBaseName}-${version}.aar" + } + } + } + + testOptions { + unitTests.returnDefaultValues = true + } +} + +ext { + swagger_annotations_version = "1.6.2" + gson_version = "2.8.6" + httpmime_version = "4.5.13" + volley_version = "1.2.0" + junit_version = "4.13.2" + robolectric_version = "4.5.1" + concurrent_unit_version = "0.4.6" +} + +dependencies { + implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + implementation "com.google.code.gson:gson:$gson_version" + implementation "org.apache.httpcomponents:httpmime:$httpmime_version" + implementation "com.android.volley:volley:${volley_version}" + testImplementation "junit:junit:$junit_version" + testImplementation "org.robolectric:robolectric:${robolectric_version}" + testImplementation "net.jodah:concurrentunit:${concurrent_unit_version}" +} + +afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } +} + +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} diff --git a/ems-cloud-mgmt-sdk/android/docs/Balance.md b/ems-cloud-mgmt-sdk/android/docs/Balance.md new file mode 100644 index 0000000000..0cab633749 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/Balance.md @@ -0,0 +1,14 @@ + + +# Balance + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Exchange identifier used to identify the routing destination. | [optional] +**data** | [**List<BalanceData>**](BalanceData.md) | | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/BalanceData.md b/ems-cloud-mgmt-sdk/android/docs/BalanceData.md new file mode 100644 index 0000000000..a2f913a50d --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/BalanceData.md @@ -0,0 +1,26 @@ + + +# BalanceData + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**assetIdExchange** | **String** | Exchange currency code. | [optional] +**assetIdCoinapi** | **String** | CoinAPI currency code. | [optional] +**balance** | **Double** | Value of the current total currency balance on the exchange. | [optional] +**available** | **Double** | Value of the current available currency balance on the exchange that can be used as collateral. | [optional] +**locked** | **Double** | Value of the current locked currency balance by the exchange. | [optional] +**lastUpdatedBy** | [**LastUpdatedByEnum**](#LastUpdatedByEnum) | Source of the last modification. | [optional] +**rateUsd** | **Double** | Current exchange rate to the USD for the single unit of the currency. | [optional] +**traded** | **Double** | Value of the current total traded. | [optional] + + +## Enum: LastUpdatedByEnum + +Name | Value +---- | ----- + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/BalancesApi.md b/ems-cloud-mgmt-sdk/android/docs/BalancesApi.md new file mode 100644 index 0000000000..dde823c56e --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/BalancesApi.md @@ -0,0 +1,55 @@ +# BalancesApi + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1BalancesGet**](BalancesApi.md#v1BalancesGet) | **GET** /v1/balances | Get balances + + + +## v1BalancesGet + +> List<Balance> v1BalancesGet(exchangeId) + +Get balances + +Get current currency balance from all or single exchange. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.BalancesApi; + +BalancesApi apiInstance = new BalancesApi(); +String exchangeId = KRAKEN; // String | Filter the balances to the specific exchange. +try { + List result = apiInstance.v1BalancesGet(exchangeId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling BalancesApi#v1BalancesGet"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **String**| Filter the balances to the specific exchange. | [optional] [default to null] + +### Return type + +[**List<Balance>**](Balance.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, appliction/json + diff --git a/ems-cloud-mgmt-sdk/android/docs/Fills.md b/ems-cloud-mgmt-sdk/android/docs/Fills.md new file mode 100644 index 0000000000..712af2b63f --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/Fills.md @@ -0,0 +1,15 @@ + + +# Fills + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**time** | [**Date**](Date.md) | Execution time. | [optional] +**price** | [**BigDecimal**](BigDecimal.md) | Execution price. | [optional] +**amount** | [**BigDecimal**](BigDecimal.md) | Executed quantity. | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/MessageReject.md b/ems-cloud-mgmt-sdk/android/docs/MessageReject.md new file mode 100644 index 0000000000..2b8ff9c152 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/MessageReject.md @@ -0,0 +1,17 @@ + + +# MessageReject + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **String** | Message type, constant. | [optional] +**rejectReason** | [**RejectReason**](RejectReason.md) | | [optional] +**exchangeId** | **String** | If the message related to exchange, then the identifier of the exchange will be provided. | [optional] +**message** | **String** | Message text. | [optional] +**rejectedMessage** | **String** | Value of rejected request, if available. | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrdSide.md b/ems-cloud-mgmt-sdk/android/docs/OrdSide.md new file mode 100644 index 0000000000..c759c04b99 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrdSide.md @@ -0,0 +1,10 @@ + + +# OrdSide + +## Enum + + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrdStatus.md b/ems-cloud-mgmt-sdk/android/docs/OrdStatus.md new file mode 100644 index 0000000000..accd26d02a --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrdStatus.md @@ -0,0 +1,10 @@ + + +# OrdStatus + +## Enum + + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrdType.md b/ems-cloud-mgmt-sdk/android/docs/OrdType.md new file mode 100644 index 0000000000..47cd128464 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrdType.md @@ -0,0 +1,10 @@ + + +# OrdType + +## Enum + + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrderCancelAllRequest.md b/ems-cloud-mgmt-sdk/android/docs/OrderCancelAllRequest.md new file mode 100644 index 0000000000..2a24bd42f4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrderCancelAllRequest.md @@ -0,0 +1,13 @@ + + +# OrderCancelAllRequest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Identifier of the exchange from which active orders should be canceled. | + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrderCancelSingleRequest.md b/ems-cloud-mgmt-sdk/android/docs/OrderCancelSingleRequest.md new file mode 100644 index 0000000000..d6ac12e353 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrderCancelSingleRequest.md @@ -0,0 +1,15 @@ + + +# OrderCancelSingleRequest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Exchange identifier used to identify the routing destination. | +**exchangeOrderId** | **String** | Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. | [optional] +**clientOrderId** | **String** | The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReport.md b/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReport.md new file mode 100644 index 0000000000..f53e06b1d4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReport.md @@ -0,0 +1,41 @@ + + +# OrderExecutionReport + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Exchange identifier used to identify the routing destination. | +**clientOrderId** | **String** | The unique identifier of the order assigned by the client. | +**symbolIdExchange** | **String** | Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**symbolIdCoinapi** | **String** | CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**amountOrder** | [**BigDecimal**](BigDecimal.md) | Order quantity. | +**price** | [**BigDecimal**](BigDecimal.md) | Order price. | +**side** | [**OrdSide**](OrdSide.md) | | +**orderType** | [**OrdType**](OrdType.md) | | +**timeInForce** | [**TimeInForce**](TimeInForce.md) | | +**expireTime** | [**Date**](Date.md) | Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. | [optional] +**execInst** | [**List<ExecInstEnum>**](#List<ExecInstEnum>) | Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> | [optional] +**clientOrderIdFormatExchange** | **String** | The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. | +**exchangeOrderId** | **String** | Unique identifier of the order assigned by the exchange or executing system. | [optional] +**amountOpen** | [**BigDecimal**](BigDecimal.md) | Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` | +**amountFilled** | [**BigDecimal**](BigDecimal.md) | Total quantity filled. | +**avgPx** | [**BigDecimal**](BigDecimal.md) | Calculated average price of all fills on this order. | [optional] +**status** | [**OrdStatus**](OrdStatus.md) | | +**statusHistory** | [**List<List<String>>**](List.md) | Timestamped history of order status changes. | [optional] +**errorMessage** | **String** | Error message. | [optional] +**fills** | [**List<Fills>**](Fills.md) | Relay fill information on working orders. | [optional] + + +## Enum: List<ExecInstEnum> + +Name | Value +---- | ----- +MAKER_OR_CANCEL | "MAKER_OR_CANCEL" +AUCTION_ONLY | "AUCTION_ONLY" +INDICATION_OF_INTEREST | "INDICATION_OF_INTEREST" + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReportAllOf.md b/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReportAllOf.md new file mode 100644 index 0000000000..e7bc6001d7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrderExecutionReportAllOf.md @@ -0,0 +1,21 @@ + + +# OrderExecutionReportAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**clientOrderIdFormatExchange** | **String** | The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. | +**exchangeOrderId** | **String** | Unique identifier of the order assigned by the exchange or executing system. | [optional] +**amountOpen** | [**BigDecimal**](BigDecimal.md) | Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` | +**amountFilled** | [**BigDecimal**](BigDecimal.md) | Total quantity filled. | +**avgPx** | [**BigDecimal**](BigDecimal.md) | Calculated average price of all fills on this order. | [optional] +**status** | [**OrdStatus**](OrdStatus.md) | | +**statusHistory** | [**List<List<String>>**](List.md) | Timestamped history of order status changes. | [optional] +**errorMessage** | **String** | Error message. | [optional] +**fills** | [**List<Fills>**](Fills.md) | Relay fill information on working orders. | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrderNewSingleRequest.md b/ems-cloud-mgmt-sdk/android/docs/OrderNewSingleRequest.md new file mode 100644 index 0000000000..15f63b01ad --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrderNewSingleRequest.md @@ -0,0 +1,32 @@ + + +# OrderNewSingleRequest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Exchange identifier used to identify the routing destination. | +**clientOrderId** | **String** | The unique identifier of the order assigned by the client. | +**symbolIdExchange** | **String** | Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**symbolIdCoinapi** | **String** | CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**amountOrder** | [**BigDecimal**](BigDecimal.md) | Order quantity. | +**price** | [**BigDecimal**](BigDecimal.md) | Order price. | +**side** | [**OrdSide**](OrdSide.md) | | +**orderType** | [**OrdType**](OrdType.md) | | +**timeInForce** | [**TimeInForce**](TimeInForce.md) | | +**expireTime** | [**Date**](Date.md) | Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. | [optional] +**execInst** | [**List<ExecInstEnum>**](#List<ExecInstEnum>) | Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> | [optional] + + +## Enum: List<ExecInstEnum> + +Name | Value +---- | ----- +MAKER_OR_CANCEL | "MAKER_OR_CANCEL" +AUCTION_ONLY | "AUCTION_ONLY" +INDICATION_OF_INTEREST | "INDICATION_OF_INTEREST" + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/OrdersApi.md b/ems-cloud-mgmt-sdk/android/docs/OrdersApi.md new file mode 100644 index 0000000000..a17ec5c853 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/OrdersApi.md @@ -0,0 +1,243 @@ +# OrdersApi + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1OrdersCancelAllPost**](OrdersApi.md#v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +[**v1OrdersCancelPost**](OrdersApi.md#v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +[**v1OrdersGet**](OrdersApi.md#v1OrdersGet) | **GET** /v1/orders | Get open orders +[**v1OrdersPost**](OrdersApi.md#v1OrdersPost) | **POST** /v1/orders | Send new order +[**v1OrdersStatusClientOrderIdGet**](OrdersApi.md#v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report + + + +## v1OrdersCancelAllPost + +> MessageReject v1OrdersCancelAllPost(orderCancelAllRequest) + +Cancel all orders request + +This request cancels all open orders on single specified exchange. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.OrdersApi; + +OrdersApi apiInstance = new OrdersApi(); +OrderCancelAllRequest orderCancelAllRequest = new OrderCancelAllRequest(); // OrderCancelAllRequest | OrderCancelAllRequest object. +try { + MessageReject result = apiInstance.v1OrdersCancelAllPost(orderCancelAllRequest); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling OrdersApi#v1OrdersCancelAllPost"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderCancelAllRequest** | [**OrderCancelAllRequest**](OrderCancelAllRequest.md)| OrderCancelAllRequest object. | + +### Return type + +[**MessageReject**](MessageReject.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + + +## v1OrdersCancelPost + +> OrderExecutionReport v1OrdersCancelPost(orderCancelSingleRequest) + +Cancel order request + +Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.OrdersApi; + +OrdersApi apiInstance = new OrdersApi(); +OrderCancelSingleRequest orderCancelSingleRequest = new OrderCancelSingleRequest(); // OrderCancelSingleRequest | OrderCancelSingleRequest object. +try { + OrderExecutionReport result = apiInstance.v1OrdersCancelPost(orderCancelSingleRequest); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling OrdersApi#v1OrdersCancelPost"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderCancelSingleRequest** | [**OrderCancelSingleRequest**](OrderCancelSingleRequest.md)| OrderCancelSingleRequest object. | + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + + +## v1OrdersGet + +> List<OrderExecutionReport> v1OrdersGet(exchangeId) + +Get open orders + +Get last execution reports for open orders across all or single exchange. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.OrdersApi; + +OrdersApi apiInstance = new OrdersApi(); +String exchangeId = KRAKEN; // String | Filter the open orders to the specific exchange. +try { + List result = apiInstance.v1OrdersGet(exchangeId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling OrdersApi#v1OrdersGet"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **String**| Filter the open orders to the specific exchange. | [optional] [default to null] + +### Return type + +[**List<OrderExecutionReport>**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, appliction/json + + +## v1OrdersPost + +> OrderExecutionReport v1OrdersPost(orderNewSingleRequest) + +Send new order + +This request creating new order for the specific exchange. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.OrdersApi; + +OrdersApi apiInstance = new OrdersApi(); +OrderNewSingleRequest orderNewSingleRequest = new OrderNewSingleRequest(); // OrderNewSingleRequest | OrderNewSingleRequest object. +try { + OrderExecutionReport result = apiInstance.v1OrdersPost(orderNewSingleRequest); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling OrdersApi#v1OrdersPost"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderNewSingleRequest** | [**OrderNewSingleRequest**](OrderNewSingleRequest.md)| OrderNewSingleRequest object. | + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + + +## v1OrdersStatusClientOrderIdGet + +> OrderExecutionReport v1OrdersStatusClientOrderIdGet(clientOrderId) + +Get order execution report + +Get the last order execution report for the specified order. The requested order does not need to be active or opened. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.OrdersApi; + +OrdersApi apiInstance = new OrdersApi(); +String clientOrderId = 6ab36bc1-344d-432e-ac6d-0bf44ee64c2b; // String | The unique identifier of the order assigned by the client. +try { + OrderExecutionReport result = apiInstance.v1OrdersStatusClientOrderIdGet(clientOrderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling OrdersApi#v1OrdersStatusClientOrderIdGet"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **clientOrderId** | **String**| The unique identifier of the order assigned by the client. | [default to null] + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + diff --git a/ems-cloud-mgmt-sdk/android/docs/Position.md b/ems-cloud-mgmt-sdk/android/docs/Position.md new file mode 100644 index 0000000000..628118d5cb --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/Position.md @@ -0,0 +1,14 @@ + + +# Position + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeId** | **String** | Exchange identifier used to identify the routing destination. | [optional] +**data** | [**List<PositionData>**](PositionData.md) | | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/PositionData.md b/ems-cloud-mgmt-sdk/android/docs/PositionData.md new file mode 100644 index 0000000000..c4601acffe --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/PositionData.md @@ -0,0 +1,22 @@ + + +# PositionData + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbolIdExchange** | **String** | Exchange symbol. | [optional] +**symbolIdCoinapi** | **String** | CoinAPI symbol. | [optional] +**avgEntryPrice** | [**BigDecimal**](BigDecimal.md) | Calculated average price of all fills on this position. | [optional] +**quantity** | [**BigDecimal**](BigDecimal.md) | The current position quantity. | [optional] +**side** | [**OrdSide**](OrdSide.md) | | [optional] +**unrealizedPnl** | [**BigDecimal**](BigDecimal.md) | Unrealised profit or loss (PNL) of this position. | [optional] +**leverage** | [**BigDecimal**](BigDecimal.md) | Leverage for this position reported by the exchange. | [optional] +**crossMargin** | **Boolean** | Is cross margin mode enable for this position? | [optional] +**liquidationPrice** | [**BigDecimal**](BigDecimal.md) | Liquidation price. If mark price will reach this value, the position will be liquidated. | [optional] +**rawData** | **Object** | | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/PositionsApi.md b/ems-cloud-mgmt-sdk/android/docs/PositionsApi.md new file mode 100644 index 0000000000..f1bf060210 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/PositionsApi.md @@ -0,0 +1,55 @@ +# PositionsApi + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1PositionsGet**](PositionsApi.md#v1PositionsGet) | **GET** /v1/positions | Get open positions + + + +## v1PositionsGet + +> List<Position> v1PositionsGet(exchangeId) + +Get open positions + +Get current open positions across all or single exchange. + +### Example + +```java +// Import classes: +//import org.openapitools.client.api.PositionsApi; + +PositionsApi apiInstance = new PositionsApi(); +String exchangeId = KRAKEN; // String | Filter the balances to the specific exchange. +try { + List result = apiInstance.v1PositionsGet(exchangeId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PositionsApi#v1PositionsGet"); + e.printStackTrace(); +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **String**| Filter the balances to the specific exchange. | [optional] [default to null] + +### Return type + +[**List<Position>**](Position.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, appliction/json + diff --git a/ems-cloud-mgmt-sdk/android/docs/RejectReason.md b/ems-cloud-mgmt-sdk/android/docs/RejectReason.md new file mode 100644 index 0000000000..1a04aa9d07 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/RejectReason.md @@ -0,0 +1,10 @@ + + +# RejectReason + +## Enum + + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/TimeInForce.md b/ems-cloud-mgmt-sdk/android/docs/TimeInForce.md new file mode 100644 index 0000000000..3da603fb60 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/TimeInForce.md @@ -0,0 +1,10 @@ + + +# TimeInForce + +## Enum + + + + + diff --git a/ems-cloud-mgmt-sdk/android/docs/ValidationError.md b/ems-cloud-mgmt-sdk/android/docs/ValidationError.md new file mode 100644 index 0000000000..2be480d0f1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/docs/ValidationError.md @@ -0,0 +1,17 @@ + + +# ValidationError + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **String** | | [optional] +**title** | **String** | | [optional] +**status** | [**BigDecimal**](BigDecimal.md) | | [optional] +**traceId** | **String** | | [optional] +**errors** | **String** | | [optional] + + + + diff --git a/ems-cloud-mgmt-sdk/android/git_push.sh b/ems-cloud-mgmt-sdk/android/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.jar b/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..e708b1c023 Binary files /dev/null and b/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.properties b/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..4d9ca16491 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/ems-cloud-mgmt-sdk/android/gradlew b/ems-cloud-mgmt-sdk/android/gradlew new file mode 100644 index 0000000000..4f906e0c81 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/ems-cloud-mgmt-sdk/android/gradlew.bat b/ems-cloud-mgmt-sdk/android/gradlew.bat new file mode 100644 index 0000000000..107acd32c4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/ems-cloud-mgmt-sdk/android/pom.xml b/ems-cloud-mgmt-sdk/android/pom.xml new file mode 100644 index 0000000000..42a819516d --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + org.openapitools + openapi-android-client + 1.0.0 + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + org.apache.httpcomponents + httpmime + ${httpcomponents-httpmime-version} + + + com.google.code.gson + gson + ${google-code-gson-version} + + + com.mcxiaoke.volley + library + ${volley-library-version} + + + com.google.android + android + ${android-platform-version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.7 + 1.7 + + + + + + 1.5.8 + 4.5.2 + 2.6.2 + 1.0.19 + 4.1.1.4 + + diff --git a/ems-cloud-mgmt-sdk/android/src/main/AndroidManifest.xml b/ems-cloud-mgmt-sdk/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..90fc37cd89 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiException.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 0000000000..03701e026a --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,61 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +public class ApiException extends Exception { + int code = 0; + String message = null; + + public ApiException() {} + + public ApiException(int code, String message) { + this.code = code; + this.message = message; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Set the HTTP status code. + * + * @param code HTTP status code. + */ + public void setCode(int code) { + this.code = code; + } + + /** + * Get the error message. + * + * @return Error message. + */ + public String getMessage() { + return message; + } + + /** + * Set the error messages. + * + * @param message Error message. + */ + public void setMessage(String message) { + this.message = message; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiInvoker.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiInvoker.java new file mode 100644 index 0000000000..bf656ee82d --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/ApiInvoker.java @@ -0,0 +1,529 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.android.volley.Cache; +import com.android.volley.DefaultRetryPolicy; +import com.android.volley.Network; +import com.android.volley.Request; +import com.android.volley.RequestQueue; +import com.android.volley.Response; +import com.android.volley.ResponseDelivery; +import com.android.volley.toolbox.BasicNetwork; +import com.android.volley.toolbox.HttpStack; +import com.android.volley.toolbox.HurlStack; +import com.android.volley.toolbox.NoCache; +import com.android.volley.toolbox.RequestFuture; +import com.google.gson.JsonParseException; + +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.ApiKeyAuth; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.request.GetRequest; +import org.openapitools.client.request.PostRequest; +import org.openapitools.client.request.PutRequest; +import org.openapitools.client.request.DeleteRequest; +import org.openapitools.client.request.PatchRequest; + +public class ApiInvoker { + private static ApiInvoker INSTANCE; + private Map defaultHeaderMap = new HashMap(); + + private RequestQueue mRequestQueue; + + private Map authentications; + + private int connectionTimeout; + + /** Content type "text/plain" with UTF-8 encoding. */ + public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); + + /** + * ISO 8601 date time format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + /** + * ISO 8601 date format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + static { + // Use UTC as the default time zone. + DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + public static void setUserAgent(String userAgent) { + INSTANCE.addDefaultHeader("User-Agent", userAgent); + } + + public static Date parseDateTime(String str) { + try { + return DATE_TIME_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static Date parseDate(String str) { + try { + return DATE_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static String formatDateTime(Date datetime) { + return DATE_TIME_FORMAT.format(datetime); + } + + public static String formatDate(Date date) { + return DATE_FORMAT.format(date); + } + + public static String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDateTime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public static List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + public static void initializeInstance() { + initializeInstance(null); + } + + public static void initializeInstance(Cache cache) { + initializeInstance(cache, null, 0, null, 30); + } + + public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { + INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); + setUserAgent("OpenAPI-Generator/1.0.0/android"); + + // Setup authentications (key: authentication name, value: authentication). + INSTANCE.authentications = new HashMap(); + // Prevent the authentications from being modified. + INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); + } + + private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { + if(cache == null) cache = new NoCache(); + if(network == null) { + HttpStack stack = new HurlStack(); + network = new BasicNetwork(stack); + } + + if(delivery == null) { + initConnectionRequest(cache, network); + } else { + initConnectionRequest(cache, network, threadPoolSize, delivery); + } + this.connectionTimeout = connectionTimeout; + } + + public static ApiInvoker getInstance() { + if (INSTANCE == null) initializeInstance(); + return INSTANCE; + } + + public void addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + } + + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + try{ + if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) { + return JsonUtil.deserializeToList(json, cls); + } + else if(String.class.equals(cls)) { + if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) + return json.substring(1, json.length() - 1); + else + return json; + } + else { + return JsonUtil.deserializeToObject(json, cls); + } + } + catch (JsonParseException e) { + throw new ApiException(500, e.getMessage()); + } + } + + public static String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return JsonUtil.serialize(obj); + else + return null; + } + catch (Exception e) { + throw new ApiException(500, e.getMessage()); + } + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + public void setConnectionTimeout(int connectionTimeout){ + this.connectionTimeout = connectionTimeout; + } + + public int getConnectionTimeout() { + return connectionTimeout; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { + try { + RequestFuture future = RequestFuture.newFuture(); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); + if(request != null) { + mRequestQueue.add(request); + return future.get(connectionTimeout, TimeUnit.SECONDS); + } else { + return "no data"; + } + } catch (UnsupportedEncodingException ex) { + throw new ApiException(0, "UnsupportedEncodingException"); + } + } + + public void invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { + try { + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); + if (request != null) { + mRequestQueue.add(request); + } + } catch (UnsupportedEncodingException ex) { + throw new ApiException(0, "UnsupportedEncodingException"); + } + } + + public Request createRequest(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException, UnsupportedEncodingException { + StringBuilder b = new StringBuilder(); + b.append("?"); + + updateParamsForAuth(authNames, queryParams, headerParams); + + if (queryParams != null){ + for (Pair queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); + b.append("&"); + } + } + } + + String querystring = b.substring(0, b.length() - 1); + String url = host + path + querystring; + + HashMap headers = new HashMap(); + + for(String key : headerParams.keySet()) { + headers.put(key, headerParams.get(key)); + } + + for(String key : defaultHeaderMap.keySet()) { + if(!headerParams.containsKey(key)) { + headers.put(key, defaultHeaderMap.get(key)); + } + } + headers.put("Accept", "application/json"); + + // URL encoded string from form parameters + String formParamStr = null; + + // for form data + if ("application/x-www-form-urlencoded".equals(contentType)) { + StringBuilder formParamBuilder = new StringBuilder(); + + // encode the form params + for (String key : formParams.keySet()) { + String value = formParams.get(key); + if (value != null && !"".equals(value.trim())) { + if (formParamBuilder.length() > 0) { + formParamBuilder.append("&"); + } + try { + formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); + } + catch (Exception e) { + // move on to next + } + } + } + formParamStr = formParamBuilder.toString(); + } + Request request = null; + + if ("GET".equals(method)) { + request = new GetRequest(url, headers, null, stringRequest, errorListener); + } + else if ("POST".equals(method)) { + request = null; + if (formParamStr != null) { + request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); + } else if (body != null) { + if (body instanceof HttpEntity) { + request = new PostRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener); + } else { + request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); + } + } else { + request = new PostRequest(url, headers, null, null, stringRequest, errorListener); + } + } + else if ("PUT".equals(method)) { + request = null; + if (formParamStr != null) { + request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); + } else if (body != null) { + if (body instanceof HttpEntity) { + request = new PutRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener); + } else { + request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); + } + } else { + request = new PutRequest(url, headers, null, null, stringRequest, errorListener); + } + } + else if ("DELETE".equals(method)) { + request = null; + if (formParamStr != null) { + request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); + } else if (body != null) { + if (body instanceof HttpEntity) { + request = new DeleteRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener); + } else { + request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); + } + } else { + request = new DeleteRequest(url, headers, null, null, stringRequest, errorListener); + } + } + else if ("PATCH".equals(method)) { + request = null; + if (formParamStr != null) { + request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); + } else if (body != null) { + if (body instanceof HttpEntity) { + request = new PatchRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener); + } else { + request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); + } + } else { + request = new PatchRequest(url, headers, null, null, stringRequest, errorListener); + } + } + + if (request != null) { + request.setRetryPolicy(new DefaultRetryPolicy((int)TimeUnit.SECONDS.toMillis(this.connectionTimeout), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); + } + + return request; + } + + private void initConnectionRequest(Cache cache, Network network) { + mRequestQueue = new RequestQueue(cache, network); + mRequestQueue.start(); + } + + private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { + mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); + mRequestQueue.start(); + } + + public void stopQueue() { + mRequestQueue.stop(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/JsonUtil.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/JsonUtil.java new file mode 100644 index 0000000000..c3263ee491 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/JsonUtil.java @@ -0,0 +1,205 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Date; +import org.openapitools.client.model.*; + +public class JsonUtil { + public static GsonBuilder gsonBuilder; + + static { + gsonBuilder = new GsonBuilder(); + gsonBuilder.serializeNulls(); + gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + } + + public static Gson getGson() { + return gsonBuilder.create(); + } + + public static String serialize(Object obj){ + return getGson().toJson(obj); + } + + public static T deserializeToList(String jsonString, Class cls){ + return getGson().fromJson(jsonString, getListTypeForDeserialization(cls)); + } + + public static T deserializeToObject(String jsonString, Class cls){ + return getGson().fromJson(jsonString, getTypeForDeserialization(cls)); + } + + public static Type getListTypeForDeserialization(Class cls) { + String className = cls.getSimpleName(); + + if ("Balance".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("BalanceData".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Fills".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("MessageReject".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrdSide".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrdStatus".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrdType".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrderCancelAllRequest".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrderCancelSingleRequest".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrderExecutionReport".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrderExecutionReportAllOf".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("OrderNewSingleRequest".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Position".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("PositionData".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("RejectReason".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("TimeInForce".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("ValidationError".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + return new TypeToken>(){}.getType(); + } + + public static Type getTypeForDeserialization(Class cls) { + String className = cls.getSimpleName(); + + if ("Balance".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("BalanceData".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Fills".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("MessageReject".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrdSide".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrdStatus".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrdType".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrderCancelAllRequest".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrderCancelSingleRequest".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrderExecutionReport".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrderExecutionReportAllOf".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("OrderNewSingleRequest".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Position".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("PositionData".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("RejectReason".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("TimeInForce".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("ValidationError".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + return new TypeToken(){}.getType(); + } + +}; diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/Pair.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 0000000000..fc6e7dcc78 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,50 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair(String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/BalancesApi.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/BalancesApi.java new file mode 100644 index 0000000000..530a59c08d --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/BalancesApi.java @@ -0,0 +1,178 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiInvoker; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import org.openapitools.client.model.*; + +import java.util.*; + +import com.android.volley.Response; +import com.android.volley.VolleyError; + +import org.openapitools.client.model.Balance; +import org.openapitools.client.model.MessageReject; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +public class BalancesApi { + String basePath = "https://ems-gateway-aws-eu-central-1-dev.coinapi.io"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + /** + * Get balances + * Get current currency balance from all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. + * @return List + */ + public List v1BalancesGet (String exchangeId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // create path and map variables + String path = "/v1/balances"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (List) ApiInvoker.deserialize(localVarResponse, "array", Balance.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Get balances + * Get current currency balance from all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. + */ + public void v1BalancesGet (String exchangeId, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // create path and map variables + String path = "/v1/balances".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((List) ApiInvoker.deserialize(localVarResponse, "array", Balance.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/OrdersApi.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/OrdersApi.java new file mode 100644 index 0000000000..d822e69a5c --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/OrdersApi.java @@ -0,0 +1,693 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiInvoker; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import org.openapitools.client.model.*; + +import java.util.*; + +import com.android.volley.Response; +import com.android.volley.VolleyError; + +import org.openapitools.client.model.MessageReject; +import org.openapitools.client.model.OrderCancelAllRequest; +import org.openapitools.client.model.OrderCancelSingleRequest; +import org.openapitools.client.model.OrderExecutionReport; +import org.openapitools.client.model.OrderNewSingleRequest; +import org.openapitools.client.model.ValidationError; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +public class OrdersApi { + String basePath = "https://ems-gateway-aws-eu-central-1-dev.coinapi.io"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + /** + * Cancel all orders request + * This request cancels all open orders on single specified exchange. + * @param orderCancelAllRequest OrderCancelAllRequest object. + * @return MessageReject + */ + public MessageReject v1OrdersCancelAllPost (OrderCancelAllRequest orderCancelAllRequest) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = orderCancelAllRequest; + // verify the required parameter 'orderCancelAllRequest' is set + if (orderCancelAllRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderCancelAllRequest' when calling v1OrdersCancelAllPost", + new ApiException(400, "Missing the required parameter 'orderCancelAllRequest' when calling v1OrdersCancelAllPost")); + } + + // create path and map variables + String path = "/v1/orders/cancel/all"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (MessageReject) ApiInvoker.deserialize(localVarResponse, "", MessageReject.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Cancel all orders request + * This request cancels all open orders on single specified exchange. + * @param orderCancelAllRequest OrderCancelAllRequest object. + */ + public void v1OrdersCancelAllPost (OrderCancelAllRequest orderCancelAllRequest, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = orderCancelAllRequest; + + // verify the required parameter 'orderCancelAllRequest' is set + if (orderCancelAllRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderCancelAllRequest' when calling v1OrdersCancelAllPost", + new ApiException(400, "Missing the required parameter 'orderCancelAllRequest' when calling v1OrdersCancelAllPost")); + } + + // create path and map variables + String path = "/v1/orders/cancel/all".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((MessageReject) ApiInvoker.deserialize(localVarResponse, "", MessageReject.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** + * Cancel order request + * Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + * @param orderCancelSingleRequest OrderCancelSingleRequest object. + * @return OrderExecutionReport + */ + public OrderExecutionReport v1OrdersCancelPost (OrderCancelSingleRequest orderCancelSingleRequest) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = orderCancelSingleRequest; + // verify the required parameter 'orderCancelSingleRequest' is set + if (orderCancelSingleRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderCancelSingleRequest' when calling v1OrdersCancelPost", + new ApiException(400, "Missing the required parameter 'orderCancelSingleRequest' when calling v1OrdersCancelPost")); + } + + // create path and map variables + String path = "/v1/orders/cancel"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Cancel order request + * Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + * @param orderCancelSingleRequest OrderCancelSingleRequest object. + */ + public void v1OrdersCancelPost (OrderCancelSingleRequest orderCancelSingleRequest, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = orderCancelSingleRequest; + + // verify the required parameter 'orderCancelSingleRequest' is set + if (orderCancelSingleRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderCancelSingleRequest' when calling v1OrdersCancelPost", + new ApiException(400, "Missing the required parameter 'orderCancelSingleRequest' when calling v1OrdersCancelPost")); + } + + // create path and map variables + String path = "/v1/orders/cancel".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** + * Get open orders + * Get last execution reports for open orders across all or single exchange. + * @param exchangeId Filter the open orders to the specific exchange. + * @return List + */ + public List v1OrdersGet (String exchangeId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // create path and map variables + String path = "/v1/orders"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (List) ApiInvoker.deserialize(localVarResponse, "array", OrderExecutionReport.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Get open orders + * Get last execution reports for open orders across all or single exchange. + * @param exchangeId Filter the open orders to the specific exchange. + */ + public void v1OrdersGet (String exchangeId, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // create path and map variables + String path = "/v1/orders".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((List) ApiInvoker.deserialize(localVarResponse, "array", OrderExecutionReport.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** + * Send new order + * This request creating new order for the specific exchange. + * @param orderNewSingleRequest OrderNewSingleRequest object. + * @return OrderExecutionReport + */ + public OrderExecutionReport v1OrdersPost (OrderNewSingleRequest orderNewSingleRequest) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = orderNewSingleRequest; + // verify the required parameter 'orderNewSingleRequest' is set + if (orderNewSingleRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderNewSingleRequest' when calling v1OrdersPost", + new ApiException(400, "Missing the required parameter 'orderNewSingleRequest' when calling v1OrdersPost")); + } + + // create path and map variables + String path = "/v1/orders"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Send new order + * This request creating new order for the specific exchange. + * @param orderNewSingleRequest OrderNewSingleRequest object. + */ + public void v1OrdersPost (OrderNewSingleRequest orderNewSingleRequest, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = orderNewSingleRequest; + + // verify the required parameter 'orderNewSingleRequest' is set + if (orderNewSingleRequest == null) { + VolleyError error = new VolleyError("Missing the required parameter 'orderNewSingleRequest' when calling v1OrdersPost", + new ApiException(400, "Missing the required parameter 'orderNewSingleRequest' when calling v1OrdersPost")); + } + + // create path and map variables + String path = "/v1/orders".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + String[] contentTypes = { + "application/json" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } + /** + * Get order execution report + * Get the last order execution report for the specified order. The requested order does not need to be active or opened. + * @param clientOrderId The unique identifier of the order assigned by the client. + * @return OrderExecutionReport + */ + public OrderExecutionReport v1OrdersStatusClientOrderIdGet (String clientOrderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + // verify the required parameter 'clientOrderId' is set + if (clientOrderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'clientOrderId' when calling v1OrdersStatusClientOrderIdGet", + new ApiException(400, "Missing the required parameter 'clientOrderId' when calling v1OrdersStatusClientOrderIdGet")); + } + + // create path and map variables + String path = "/v1/orders/status/{client_order_id}".replaceAll("\\{" + "client_order_id" + "\\}", apiInvoker.escapeString(clientOrderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Get order execution report + * Get the last order execution report for the specified order. The requested order does not need to be active or opened. + * @param clientOrderId The unique identifier of the order assigned by the client. + */ + public void v1OrdersStatusClientOrderIdGet (String clientOrderId, final Response.Listener responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + // verify the required parameter 'clientOrderId' is set + if (clientOrderId == null) { + VolleyError error = new VolleyError("Missing the required parameter 'clientOrderId' when calling v1OrdersStatusClientOrderIdGet", + new ApiException(400, "Missing the required parameter 'clientOrderId' when calling v1OrdersStatusClientOrderIdGet")); + } + + // create path and map variables + String path = "/v1/orders/status/{client_order_id}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "client_order_id" + "\\}", apiInvoker.escapeString(clientOrderId.toString())); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((OrderExecutionReport) ApiInvoker.deserialize(localVarResponse, "", OrderExecutionReport.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/PositionsApi.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/PositionsApi.java new file mode 100644 index 0000000000..26ef2533b7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/api/PositionsApi.java @@ -0,0 +1,178 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiInvoker; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import org.openapitools.client.model.*; + +import java.util.*; + +import com.android.volley.Response; +import com.android.volley.VolleyError; + +import org.openapitools.client.model.MessageReject; +import org.openapitools.client.model.Position; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +public class PositionsApi { + String basePath = "https://ems-gateway-aws-eu-central-1-dev.coinapi.io"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + /** + * Get open positions + * Get current open positions across all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. + * @return List + */ + public List v1PositionsGet (String exchangeId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { + Object postBody = null; + + // create path and map variables + String path = "/v1/positions"; + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (List) ApiInvoker.deserialize(localVarResponse, "array", Position.class); + } else { + return null; + } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } + } + + /** + * Get open positions + * Get current open positions across all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. + */ + public void v1PositionsGet (String exchangeId, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { + Object postBody = null; + + + // create path and map variables + String path = "/v1/positions".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + + queryParams.addAll(ApiInvoker.parameterToPairs("", "exchange_id", exchangeId)); + + + String[] contentTypes = { + + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); + + + HttpEntity httpEntity = localVarBuilder.build(); + postBody = httpEntity; + } else { + // normal form params + } + + String[] authNames = new String[] { }; + + try { + apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames, + new Response.Listener() { + @Override + public void onResponse(String localVarResponse) { + try { + responseListener.onResponse((List) ApiInvoker.deserialize(localVarResponse, "array", Position.class)); + } catch (ApiException exception) { + errorListener.onErrorResponse(new VolleyError(exception)); + } + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + errorListener.onErrorResponse(error); + } + }); + } catch (ApiException ex) { + errorListener.onErrorResponse(new VolleyError(ex)); + } + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 0000000000..62fe5dea96 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,73 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Map; +import java.util.List; + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKey == null) { + return; + } + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/Authentication.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 0000000000..0cba38bc52 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,23 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 0000000000..a4f65cb972 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,47 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import android.util.Base64; + +import java.util.Map; +import java.util.List; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT)); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Balance.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Balance.java new file mode 100644 index 0000000000..53e432492d --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Balance.java @@ -0,0 +1,81 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.util.*; +import org.openapitools.client.model.BalanceData; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class Balance { + + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("data") + private List data = null; + + /** + * Exchange identifier used to identify the routing destination. + **/ + @ApiModelProperty(value = "Exchange identifier used to identify the routing destination.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + **/ + @ApiModelProperty(value = "") + public List getData() { + return data; + } + public void setData(List data) { + this.data = data; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Balance balance = (Balance) o; + return (this.exchangeId == null ? balance.exchangeId == null : this.exchangeId.equals(balance.exchangeId)) && + (this.data == null ? balance.data == null : this.data.equals(balance.data)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.data == null ? 0: this.data.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Balance {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" data: ").append(data).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/BalanceData.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/BalanceData.java new file mode 100644 index 0000000000..866a591845 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/BalanceData.java @@ -0,0 +1,179 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class BalanceData { + + @SerializedName("asset_id_exchange") + private String assetIdExchange = null; + @SerializedName("asset_id_coinapi") + private String assetIdCoinapi = null; + @SerializedName("balance") + private Double balance = null; + @SerializedName("available") + private Double available = null; + @SerializedName("locked") + private Double locked = null; + public enum LastUpdatedByEnum { + INITIALIZATION, BALANCE_MANAGER, EXCHANGE, + }; + @SerializedName("last_updated_by") + private LastUpdatedByEnum lastUpdatedBy = null; + @SerializedName("rate_usd") + private Double rateUsd = null; + @SerializedName("traded") + private Double traded = null; + + /** + * Exchange currency code. + **/ + @ApiModelProperty(value = "Exchange currency code.") + public String getAssetIdExchange() { + return assetIdExchange; + } + public void setAssetIdExchange(String assetIdExchange) { + this.assetIdExchange = assetIdExchange; + } + + /** + * CoinAPI currency code. + **/ + @ApiModelProperty(value = "CoinAPI currency code.") + public String getAssetIdCoinapi() { + return assetIdCoinapi; + } + public void setAssetIdCoinapi(String assetIdCoinapi) { + this.assetIdCoinapi = assetIdCoinapi; + } + + /** + * Value of the current total currency balance on the exchange. + **/ + @ApiModelProperty(value = "Value of the current total currency balance on the exchange.") + public Double getBalance() { + return balance; + } + public void setBalance(Double balance) { + this.balance = balance; + } + + /** + * Value of the current available currency balance on the exchange that can be used as collateral. + **/ + @ApiModelProperty(value = "Value of the current available currency balance on the exchange that can be used as collateral.") + public Double getAvailable() { + return available; + } + public void setAvailable(Double available) { + this.available = available; + } + + /** + * Value of the current locked currency balance by the exchange. + **/ + @ApiModelProperty(value = "Value of the current locked currency balance by the exchange.") + public Double getLocked() { + return locked; + } + public void setLocked(Double locked) { + this.locked = locked; + } + + /** + * Source of the last modification. + **/ + @ApiModelProperty(value = "Source of the last modification. ") + public LastUpdatedByEnum getLastUpdatedBy() { + return lastUpdatedBy; + } + public void setLastUpdatedBy(LastUpdatedByEnum lastUpdatedBy) { + this.lastUpdatedBy = lastUpdatedBy; + } + + /** + * Current exchange rate to the USD for the single unit of the currency. + **/ + @ApiModelProperty(value = "Current exchange rate to the USD for the single unit of the currency. ") + public Double getRateUsd() { + return rateUsd; + } + public void setRateUsd(Double rateUsd) { + this.rateUsd = rateUsd; + } + + /** + * Value of the current total traded. + **/ + @ApiModelProperty(value = "Value of the current total traded.") + public Double getTraded() { + return traded; + } + public void setTraded(Double traded) { + this.traded = traded; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BalanceData balanceData = (BalanceData) o; + return (this.assetIdExchange == null ? balanceData.assetIdExchange == null : this.assetIdExchange.equals(balanceData.assetIdExchange)) && + (this.assetIdCoinapi == null ? balanceData.assetIdCoinapi == null : this.assetIdCoinapi.equals(balanceData.assetIdCoinapi)) && + (this.balance == null ? balanceData.balance == null : this.balance.equals(balanceData.balance)) && + (this.available == null ? balanceData.available == null : this.available.equals(balanceData.available)) && + (this.locked == null ? balanceData.locked == null : this.locked.equals(balanceData.locked)) && + (this.lastUpdatedBy == null ? balanceData.lastUpdatedBy == null : this.lastUpdatedBy.equals(balanceData.lastUpdatedBy)) && + (this.rateUsd == null ? balanceData.rateUsd == null : this.rateUsd.equals(balanceData.rateUsd)) && + (this.traded == null ? balanceData.traded == null : this.traded.equals(balanceData.traded)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.assetIdExchange == null ? 0: this.assetIdExchange.hashCode()); + result = 31 * result + (this.assetIdCoinapi == null ? 0: this.assetIdCoinapi.hashCode()); + result = 31 * result + (this.balance == null ? 0: this.balance.hashCode()); + result = 31 * result + (this.available == null ? 0: this.available.hashCode()); + result = 31 * result + (this.locked == null ? 0: this.locked.hashCode()); + result = 31 * result + (this.lastUpdatedBy == null ? 0: this.lastUpdatedBy.hashCode()); + result = 31 * result + (this.rateUsd == null ? 0: this.rateUsd.hashCode()); + result = 31 * result + (this.traded == null ? 0: this.traded.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BalanceData {\n"); + + sb.append(" assetIdExchange: ").append(assetIdExchange).append("\n"); + sb.append(" assetIdCoinapi: ").append(assetIdCoinapi).append("\n"); + sb.append(" balance: ").append(balance).append("\n"); + sb.append(" available: ").append(available).append("\n"); + sb.append(" locked: ").append(locked).append("\n"); + sb.append(" lastUpdatedBy: ").append(lastUpdatedBy).append("\n"); + sb.append(" rateUsd: ").append(rateUsd).append("\n"); + sb.append(" traded: ").append(traded).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Fills.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Fills.java new file mode 100644 index 0000000000..9accbd4d6e --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Fills.java @@ -0,0 +1,98 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import java.util.Date; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class Fills { + + @SerializedName("time") + private Date time = null; + @SerializedName("price") + private BigDecimal price = null; + @SerializedName("amount") + private BigDecimal amount = null; + + /** + * Execution time. + **/ + @ApiModelProperty(value = "Execution time.") + public Date getTime() { + return time; + } + public void setTime(Date time) { + this.time = time; + } + + /** + * Execution price. + **/ + @ApiModelProperty(value = "Execution price.") + public BigDecimal getPrice() { + return price; + } + public void setPrice(BigDecimal price) { + this.price = price; + } + + /** + * Executed quantity. + **/ + @ApiModelProperty(value = "Executed quantity.") + public BigDecimal getAmount() { + return amount; + } + public void setAmount(BigDecimal amount) { + this.amount = amount; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Fills fills = (Fills) o; + return (this.time == null ? fills.time == null : this.time.equals(fills.time)) && + (this.price == null ? fills.price == null : this.price.equals(fills.price)) && + (this.amount == null ? fills.amount == null : this.amount.equals(fills.amount)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.time == null ? 0: this.time.hashCode()); + result = 31 * result + (this.price == null ? 0: this.price.hashCode()); + result = 31 * result + (this.amount == null ? 0: this.amount.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Fills {\n"); + + sb.append(" time: ").append(time).append("\n"); + sb.append(" price: ").append(price).append("\n"); + sb.append(" amount: ").append(amount).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/MessageReject.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/MessageReject.java new file mode 100644 index 0000000000..90259ce116 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/MessageReject.java @@ -0,0 +1,128 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import org.openapitools.client.model.RejectReason; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class MessageReject { + + @SerializedName("type") + private String type = null; + @SerializedName("reject_reason") + private RejectReason rejectReason = null; + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("message") + private String message = null; + @SerializedName("rejected_message") + private String rejectedMessage = null; + + /** + * Message type, constant. + **/ + @ApiModelProperty(value = "Message type, constant.") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + public RejectReason getRejectReason() { + return rejectReason; + } + public void setRejectReason(RejectReason rejectReason) { + this.rejectReason = rejectReason; + } + + /** + * If the message related to exchange, then the identifier of the exchange will be provided. + **/ + @ApiModelProperty(value = "If the message related to exchange, then the identifier of the exchange will be provided.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + * Message text. + **/ + @ApiModelProperty(value = "Message text.") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + /** + * Value of rejected request, if available. + **/ + @ApiModelProperty(value = "Value of rejected request, if available.") + public String getRejectedMessage() { + return rejectedMessage; + } + public void setRejectedMessage(String rejectedMessage) { + this.rejectedMessage = rejectedMessage; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MessageReject messageReject = (MessageReject) o; + return (this.type == null ? messageReject.type == null : this.type.equals(messageReject.type)) && + (this.rejectReason == null ? messageReject.rejectReason == null : this.rejectReason.equals(messageReject.rejectReason)) && + (this.exchangeId == null ? messageReject.exchangeId == null : this.exchangeId.equals(messageReject.exchangeId)) && + (this.message == null ? messageReject.message == null : this.message.equals(messageReject.message)) && + (this.rejectedMessage == null ? messageReject.rejectedMessage == null : this.rejectedMessage.equals(messageReject.rejectedMessage)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.type == null ? 0: this.type.hashCode()); + result = 31 * result + (this.rejectReason == null ? 0: this.rejectReason.hashCode()); + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.message == null ? 0: this.message.hashCode()); + result = 31 * result + (this.rejectedMessage == null ? 0: this.rejectedMessage.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MessageReject {\n"); + + sb.append(" type: ").append(type).append("\n"); + sb.append(" rejectReason: ").append(rejectReason).append("\n"); + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append(" rejectedMessage: ").append(rejectedMessage).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdSide.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdSide.java new file mode 100644 index 0000000000..da3f121e37 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdSide.java @@ -0,0 +1,52 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Side of order. + **/ +@ApiModel(description = "Side of order. ") +public class OrdSide { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrdSide ordSide = (OrdSide) o; + return true; + } + + @Override + public int hashCode() { + int result = 17; + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrdSide {\n"); + + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdStatus.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdStatus.java new file mode 100644 index 0000000000..5851b3abdb --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdStatus.java @@ -0,0 +1,52 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Order statuses and the lifecycle are documented in the separate section: <a href=\"#ems-order-lifecycle\">EMS / Starter Guide / Order Lifecycle</a> + **/ +@ApiModel(description = "Order statuses and the lifecycle are documented in the separate section: EMS / Starter Guide / Order Lifecycle ") +public class OrdStatus { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrdStatus ordStatus = (OrdStatus) o; + return true; + } + + @Override + public int hashCode() { + int result = 17; + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrdStatus {\n"); + + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdType.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdType.java new file mode 100644 index 0000000000..df7800d8b5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrdType.java @@ -0,0 +1,52 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Order types are documented in the separate section: <a href=\"#ems-order-params-type\">EMS / Starter Guide / Order parameters / Order type</a> + **/ +@ApiModel(description = "Order types are documented in the separate section: EMS / Starter Guide / Order parameters / Order type ") +public class OrdType { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrdType ordType = (OrdType) o; + return true; + } + + @Override + public int hashCode() { + int result = 17; + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrdType {\n"); + + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelAllRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelAllRequest.java new file mode 100644 index 0000000000..f8e0ad65f7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelAllRequest.java @@ -0,0 +1,67 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Cancel all orders request object. + **/ +@ApiModel(description = "Cancel all orders request object.") +public class OrderCancelAllRequest { + + @SerializedName("exchange_id") + private String exchangeId = null; + + /** + * Identifier of the exchange from which active orders should be canceled. + **/ + @ApiModelProperty(required = true, value = "Identifier of the exchange from which active orders should be canceled.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderCancelAllRequest orderCancelAllRequest = (OrderCancelAllRequest) o; + return (this.exchangeId == null ? orderCancelAllRequest.exchangeId == null : this.exchangeId.equals(orderCancelAllRequest.exchangeId)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderCancelAllRequest {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelSingleRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelSingleRequest.java new file mode 100644 index 0000000000..173c7ecb39 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderCancelSingleRequest.java @@ -0,0 +1,99 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Cancel single order request object. + **/ +@ApiModel(description = "Cancel single order request object.") +public class OrderCancelSingleRequest { + + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("exchange_order_id") + private String exchangeOrderId = null; + @SerializedName("client_order_id") + private String clientOrderId = null; + + /** + * Exchange identifier used to identify the routing destination. + **/ + @ApiModelProperty(required = true, value = "Exchange identifier used to identify the routing destination.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + * Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + **/ + @ApiModelProperty(value = "Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") + public String getExchangeOrderId() { + return exchangeOrderId; + } + public void setExchangeOrderId(String exchangeOrderId) { + this.exchangeOrderId = exchangeOrderId; + } + + /** + * The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + **/ + @ApiModelProperty(value = "The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order.") + public String getClientOrderId() { + return clientOrderId; + } + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderCancelSingleRequest orderCancelSingleRequest = (OrderCancelSingleRequest) o; + return (this.exchangeId == null ? orderCancelSingleRequest.exchangeId == null : this.exchangeId.equals(orderCancelSingleRequest.exchangeId)) && + (this.exchangeOrderId == null ? orderCancelSingleRequest.exchangeOrderId == null : this.exchangeOrderId.equals(orderCancelSingleRequest.exchangeOrderId)) && + (this.clientOrderId == null ? orderCancelSingleRequest.clientOrderId == null : this.clientOrderId.equals(orderCancelSingleRequest.clientOrderId)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.exchangeOrderId == null ? 0: this.exchangeOrderId.hashCode()); + result = 31 * result + (this.clientOrderId == null ? 0: this.clientOrderId.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderCancelSingleRequest {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" exchangeOrderId: ").append(exchangeOrderId).append("\n"); + sb.append(" clientOrderId: ").append(clientOrderId).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReport.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReport.java new file mode 100644 index 0000000000..859cb31d35 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReport.java @@ -0,0 +1,380 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import java.util.*; +import java.util.Date; +import org.openapitools.client.model.Fills; +import org.openapitools.client.model.OrdSide; +import org.openapitools.client.model.OrdStatus; +import org.openapitools.client.model.OrdType; +import org.openapitools.client.model.OrderExecutionReportAllOf; +import org.openapitools.client.model.OrderNewSingleRequest; +import org.openapitools.client.model.TimeInForce; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * The order execution report object. + **/ +@ApiModel(description = "The order execution report object.") +public class OrderExecutionReport { + + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("client_order_id") + private String clientOrderId = null; + @SerializedName("symbol_id_exchange") + private String symbolIdExchange = null; + @SerializedName("symbol_id_coinapi") + private String symbolIdCoinapi = null; + @SerializedName("amount_order") + private BigDecimal amountOrder = null; + @SerializedName("price") + private BigDecimal price = null; + @SerializedName("side") + private OrdSide side = null; + @SerializedName("order_type") + private OrdType orderType = null; + @SerializedName("time_in_force") + private TimeInForce timeInForce = null; + @SerializedName("expire_time") + private Date expireTime = null; + public enum List<ExecInstEnum> { + MAKER_OR_CANCEL, AUCTION_ONLY, INDICATION_OF_INTEREST, + }; + @SerializedName("exec_inst") + private List execInst = null; + @SerializedName("client_order_id_format_exchange") + private String clientOrderIdFormatExchange = null; + @SerializedName("exchange_order_id") + private String exchangeOrderId = null; + @SerializedName("amount_open") + private BigDecimal amountOpen = null; + @SerializedName("amount_filled") + private BigDecimal amountFilled = null; + @SerializedName("avg_px") + private BigDecimal avgPx = null; + @SerializedName("status") + private OrdStatus status = null; + @SerializedName("status_history") + private List> statusHistory = null; + @SerializedName("error_message") + private String errorMessage = null; + @SerializedName("fills") + private List fills = null; + + /** + * Exchange identifier used to identify the routing destination. + **/ + @ApiModelProperty(required = true, value = "Exchange identifier used to identify the routing destination.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + * The unique identifier of the order assigned by the client. + **/ + @ApiModelProperty(required = true, value = "The unique identifier of the order assigned by the client.") + public String getClientOrderId() { + return clientOrderId; + } + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + /** + * Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + **/ + @ApiModelProperty(value = "Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.") + public String getSymbolIdExchange() { + return symbolIdExchange; + } + public void setSymbolIdExchange(String symbolIdExchange) { + this.symbolIdExchange = symbolIdExchange; + } + + /** + * CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + **/ + @ApiModelProperty(value = "CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.") + public String getSymbolIdCoinapi() { + return symbolIdCoinapi; + } + public void setSymbolIdCoinapi(String symbolIdCoinapi) { + this.symbolIdCoinapi = symbolIdCoinapi; + } + + /** + * Order quantity. + **/ + @ApiModelProperty(required = true, value = "Order quantity.") + public BigDecimal getAmountOrder() { + return amountOrder; + } + public void setAmountOrder(BigDecimal amountOrder) { + this.amountOrder = amountOrder; + } + + /** + * Order price. + **/ + @ApiModelProperty(required = true, value = "Order price.") + public BigDecimal getPrice() { + return price; + } + public void setPrice(BigDecimal price) { + this.price = price; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdSide getSide() { + return side; + } + public void setSide(OrdSide side) { + this.side = side; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdType getOrderType() { + return orderType; + } + public void setOrderType(OrdType orderType) { + this.orderType = orderType; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public TimeInForce getTimeInForce() { + return timeInForce; + } + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + /** + * Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + **/ + @ApiModelProperty(value = "Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`.") + public Date getExpireTime() { + return expireTime; + } + public void setExpireTime(Date expireTime) { + this.expireTime = expireTime; + } + + /** + * Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions + **/ + @ApiModelProperty(value = "Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions ") + public List getExecInst() { + return execInst; + } + public void setExecInst(List execInst) { + this.execInst = execInst; + } + + /** + * The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + **/ + @ApiModelProperty(required = true, value = "The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it.") + public String getClientOrderIdFormatExchange() { + return clientOrderIdFormatExchange; + } + public void setClientOrderIdFormatExchange(String clientOrderIdFormatExchange) { + this.clientOrderIdFormatExchange = clientOrderIdFormatExchange; + } + + /** + * Unique identifier of the order assigned by the exchange or executing system. + **/ + @ApiModelProperty(value = "Unique identifier of the order assigned by the exchange or executing system.") + public String getExchangeOrderId() { + return exchangeOrderId; + } + public void setExchangeOrderId(String exchangeOrderId) { + this.exchangeOrderId = exchangeOrderId; + } + + /** + * Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + **/ + @ApiModelProperty(required = true, value = "Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled`") + public BigDecimal getAmountOpen() { + return amountOpen; + } + public void setAmountOpen(BigDecimal amountOpen) { + this.amountOpen = amountOpen; + } + + /** + * Total quantity filled. + **/ + @ApiModelProperty(required = true, value = "Total quantity filled.") + public BigDecimal getAmountFilled() { + return amountFilled; + } + public void setAmountFilled(BigDecimal amountFilled) { + this.amountFilled = amountFilled; + } + + /** + * Calculated average price of all fills on this order. + **/ + @ApiModelProperty(value = "Calculated average price of all fills on this order.") + public BigDecimal getAvgPx() { + return avgPx; + } + public void setAvgPx(BigDecimal avgPx) { + this.avgPx = avgPx; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdStatus getStatus() { + return status; + } + public void setStatus(OrdStatus status) { + this.status = status; + } + + /** + * Timestamped history of order status changes. + **/ + @ApiModelProperty(value = "Timestamped history of order status changes.") + public List> getStatusHistory() { + return statusHistory; + } + public void setStatusHistory(List> statusHistory) { + this.statusHistory = statusHistory; + } + + /** + * Error message. + **/ + @ApiModelProperty(value = "Error message.") + public String getErrorMessage() { + return errorMessage; + } + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + /** + * Relay fill information on working orders. + **/ + @ApiModelProperty(value = "Relay fill information on working orders.") + public List getFills() { + return fills; + } + public void setFills(List fills) { + this.fills = fills; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderExecutionReport orderExecutionReport = (OrderExecutionReport) o; + return (this.exchangeId == null ? orderExecutionReport.exchangeId == null : this.exchangeId.equals(orderExecutionReport.exchangeId)) && + (this.clientOrderId == null ? orderExecutionReport.clientOrderId == null : this.clientOrderId.equals(orderExecutionReport.clientOrderId)) && + (this.symbolIdExchange == null ? orderExecutionReport.symbolIdExchange == null : this.symbolIdExchange.equals(orderExecutionReport.symbolIdExchange)) && + (this.symbolIdCoinapi == null ? orderExecutionReport.symbolIdCoinapi == null : this.symbolIdCoinapi.equals(orderExecutionReport.symbolIdCoinapi)) && + (this.amountOrder == null ? orderExecutionReport.amountOrder == null : this.amountOrder.equals(orderExecutionReport.amountOrder)) && + (this.price == null ? orderExecutionReport.price == null : this.price.equals(orderExecutionReport.price)) && + (this.side == null ? orderExecutionReport.side == null : this.side.equals(orderExecutionReport.side)) && + (this.orderType == null ? orderExecutionReport.orderType == null : this.orderType.equals(orderExecutionReport.orderType)) && + (this.timeInForce == null ? orderExecutionReport.timeInForce == null : this.timeInForce.equals(orderExecutionReport.timeInForce)) && + (this.expireTime == null ? orderExecutionReport.expireTime == null : this.expireTime.equals(orderExecutionReport.expireTime)) && + (this.execInst == null ? orderExecutionReport.execInst == null : this.execInst.equals(orderExecutionReport.execInst)) && + (this.clientOrderIdFormatExchange == null ? orderExecutionReport.clientOrderIdFormatExchange == null : this.clientOrderIdFormatExchange.equals(orderExecutionReport.clientOrderIdFormatExchange)) && + (this.exchangeOrderId == null ? orderExecutionReport.exchangeOrderId == null : this.exchangeOrderId.equals(orderExecutionReport.exchangeOrderId)) && + (this.amountOpen == null ? orderExecutionReport.amountOpen == null : this.amountOpen.equals(orderExecutionReport.amountOpen)) && + (this.amountFilled == null ? orderExecutionReport.amountFilled == null : this.amountFilled.equals(orderExecutionReport.amountFilled)) && + (this.avgPx == null ? orderExecutionReport.avgPx == null : this.avgPx.equals(orderExecutionReport.avgPx)) && + (this.status == null ? orderExecutionReport.status == null : this.status.equals(orderExecutionReport.status)) && + (this.statusHistory == null ? orderExecutionReport.statusHistory == null : this.statusHistory.equals(orderExecutionReport.statusHistory)) && + (this.errorMessage == null ? orderExecutionReport.errorMessage == null : this.errorMessage.equals(orderExecutionReport.errorMessage)) && + (this.fills == null ? orderExecutionReport.fills == null : this.fills.equals(orderExecutionReport.fills)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.clientOrderId == null ? 0: this.clientOrderId.hashCode()); + result = 31 * result + (this.symbolIdExchange == null ? 0: this.symbolIdExchange.hashCode()); + result = 31 * result + (this.symbolIdCoinapi == null ? 0: this.symbolIdCoinapi.hashCode()); + result = 31 * result + (this.amountOrder == null ? 0: this.amountOrder.hashCode()); + result = 31 * result + (this.price == null ? 0: this.price.hashCode()); + result = 31 * result + (this.side == null ? 0: this.side.hashCode()); + result = 31 * result + (this.orderType == null ? 0: this.orderType.hashCode()); + result = 31 * result + (this.timeInForce == null ? 0: this.timeInForce.hashCode()); + result = 31 * result + (this.expireTime == null ? 0: this.expireTime.hashCode()); + result = 31 * result + (this.execInst == null ? 0: this.execInst.hashCode()); + result = 31 * result + (this.clientOrderIdFormatExchange == null ? 0: this.clientOrderIdFormatExchange.hashCode()); + result = 31 * result + (this.exchangeOrderId == null ? 0: this.exchangeOrderId.hashCode()); + result = 31 * result + (this.amountOpen == null ? 0: this.amountOpen.hashCode()); + result = 31 * result + (this.amountFilled == null ? 0: this.amountFilled.hashCode()); + result = 31 * result + (this.avgPx == null ? 0: this.avgPx.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.statusHistory == null ? 0: this.statusHistory.hashCode()); + result = 31 * result + (this.errorMessage == null ? 0: this.errorMessage.hashCode()); + result = 31 * result + (this.fills == null ? 0: this.fills.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderExecutionReport {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" clientOrderId: ").append(clientOrderId).append("\n"); + sb.append(" symbolIdExchange: ").append(symbolIdExchange).append("\n"); + sb.append(" symbolIdCoinapi: ").append(symbolIdCoinapi).append("\n"); + sb.append(" amountOrder: ").append(amountOrder).append("\n"); + sb.append(" price: ").append(price).append("\n"); + sb.append(" side: ").append(side).append("\n"); + sb.append(" orderType: ").append(orderType).append("\n"); + sb.append(" timeInForce: ").append(timeInForce).append("\n"); + sb.append(" expireTime: ").append(expireTime).append("\n"); + sb.append(" execInst: ").append(execInst).append("\n"); + sb.append(" clientOrderIdFormatExchange: ").append(clientOrderIdFormatExchange).append("\n"); + sb.append(" exchangeOrderId: ").append(exchangeOrderId).append("\n"); + sb.append(" amountOpen: ").append(amountOpen).append("\n"); + sb.append(" amountFilled: ").append(amountFilled).append("\n"); + sb.append(" avgPx: ").append(avgPx).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" statusHistory: ").append(statusHistory).append("\n"); + sb.append(" errorMessage: ").append(errorMessage).append("\n"); + sb.append(" fills: ").append(fills).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReportAllOf.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReportAllOf.java new file mode 100644 index 0000000000..e434869014 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderExecutionReportAllOf.java @@ -0,0 +1,198 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import java.util.*; +import org.openapitools.client.model.Fills; +import org.openapitools.client.model.OrdStatus; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * The order execution report message. + **/ +@ApiModel(description = "The order execution report message.") +public class OrderExecutionReportAllOf { + + @SerializedName("client_order_id_format_exchange") + private String clientOrderIdFormatExchange = null; + @SerializedName("exchange_order_id") + private String exchangeOrderId = null; + @SerializedName("amount_open") + private BigDecimal amountOpen = null; + @SerializedName("amount_filled") + private BigDecimal amountFilled = null; + @SerializedName("avg_px") + private BigDecimal avgPx = null; + @SerializedName("status") + private OrdStatus status = null; + @SerializedName("status_history") + private List> statusHistory = null; + @SerializedName("error_message") + private String errorMessage = null; + @SerializedName("fills") + private List fills = null; + + /** + * The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + **/ + @ApiModelProperty(required = true, value = "The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it.") + public String getClientOrderIdFormatExchange() { + return clientOrderIdFormatExchange; + } + public void setClientOrderIdFormatExchange(String clientOrderIdFormatExchange) { + this.clientOrderIdFormatExchange = clientOrderIdFormatExchange; + } + + /** + * Unique identifier of the order assigned by the exchange or executing system. + **/ + @ApiModelProperty(value = "Unique identifier of the order assigned by the exchange or executing system.") + public String getExchangeOrderId() { + return exchangeOrderId; + } + public void setExchangeOrderId(String exchangeOrderId) { + this.exchangeOrderId = exchangeOrderId; + } + + /** + * Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + **/ + @ApiModelProperty(required = true, value = "Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled`") + public BigDecimal getAmountOpen() { + return amountOpen; + } + public void setAmountOpen(BigDecimal amountOpen) { + this.amountOpen = amountOpen; + } + + /** + * Total quantity filled. + **/ + @ApiModelProperty(required = true, value = "Total quantity filled.") + public BigDecimal getAmountFilled() { + return amountFilled; + } + public void setAmountFilled(BigDecimal amountFilled) { + this.amountFilled = amountFilled; + } + + /** + * Calculated average price of all fills on this order. + **/ + @ApiModelProperty(value = "Calculated average price of all fills on this order.") + public BigDecimal getAvgPx() { + return avgPx; + } + public void setAvgPx(BigDecimal avgPx) { + this.avgPx = avgPx; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdStatus getStatus() { + return status; + } + public void setStatus(OrdStatus status) { + this.status = status; + } + + /** + * Timestamped history of order status changes. + **/ + @ApiModelProperty(value = "Timestamped history of order status changes.") + public List> getStatusHistory() { + return statusHistory; + } + public void setStatusHistory(List> statusHistory) { + this.statusHistory = statusHistory; + } + + /** + * Error message. + **/ + @ApiModelProperty(value = "Error message.") + public String getErrorMessage() { + return errorMessage; + } + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + /** + * Relay fill information on working orders. + **/ + @ApiModelProperty(value = "Relay fill information on working orders.") + public List getFills() { + return fills; + } + public void setFills(List fills) { + this.fills = fills; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderExecutionReportAllOf orderExecutionReportAllOf = (OrderExecutionReportAllOf) o; + return (this.clientOrderIdFormatExchange == null ? orderExecutionReportAllOf.clientOrderIdFormatExchange == null : this.clientOrderIdFormatExchange.equals(orderExecutionReportAllOf.clientOrderIdFormatExchange)) && + (this.exchangeOrderId == null ? orderExecutionReportAllOf.exchangeOrderId == null : this.exchangeOrderId.equals(orderExecutionReportAllOf.exchangeOrderId)) && + (this.amountOpen == null ? orderExecutionReportAllOf.amountOpen == null : this.amountOpen.equals(orderExecutionReportAllOf.amountOpen)) && + (this.amountFilled == null ? orderExecutionReportAllOf.amountFilled == null : this.amountFilled.equals(orderExecutionReportAllOf.amountFilled)) && + (this.avgPx == null ? orderExecutionReportAllOf.avgPx == null : this.avgPx.equals(orderExecutionReportAllOf.avgPx)) && + (this.status == null ? orderExecutionReportAllOf.status == null : this.status.equals(orderExecutionReportAllOf.status)) && + (this.statusHistory == null ? orderExecutionReportAllOf.statusHistory == null : this.statusHistory.equals(orderExecutionReportAllOf.statusHistory)) && + (this.errorMessage == null ? orderExecutionReportAllOf.errorMessage == null : this.errorMessage.equals(orderExecutionReportAllOf.errorMessage)) && + (this.fills == null ? orderExecutionReportAllOf.fills == null : this.fills.equals(orderExecutionReportAllOf.fills)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.clientOrderIdFormatExchange == null ? 0: this.clientOrderIdFormatExchange.hashCode()); + result = 31 * result + (this.exchangeOrderId == null ? 0: this.exchangeOrderId.hashCode()); + result = 31 * result + (this.amountOpen == null ? 0: this.amountOpen.hashCode()); + result = 31 * result + (this.amountFilled == null ? 0: this.amountFilled.hashCode()); + result = 31 * result + (this.avgPx == null ? 0: this.avgPx.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.statusHistory == null ? 0: this.statusHistory.hashCode()); + result = 31 * result + (this.errorMessage == null ? 0: this.errorMessage.hashCode()); + result = 31 * result + (this.fills == null ? 0: this.fills.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderExecutionReportAllOf {\n"); + + sb.append(" clientOrderIdFormatExchange: ").append(clientOrderIdFormatExchange).append("\n"); + sb.append(" exchangeOrderId: ").append(exchangeOrderId).append("\n"); + sb.append(" amountOpen: ").append(amountOpen).append("\n"); + sb.append(" amountFilled: ").append(amountFilled).append("\n"); + sb.append(" avgPx: ").append(avgPx).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" statusHistory: ").append(statusHistory).append("\n"); + sb.append(" errorMessage: ").append(errorMessage).append("\n"); + sb.append(" fills: ").append(fills).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderNewSingleRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderNewSingleRequest.java new file mode 100644 index 0000000000..062b78b6cd --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/OrderNewSingleRequest.java @@ -0,0 +1,233 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import java.util.*; +import java.util.Date; +import org.openapitools.client.model.OrdSide; +import org.openapitools.client.model.OrdType; +import org.openapitools.client.model.TimeInForce; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * The new order message. + **/ +@ApiModel(description = "The new order message.") +public class OrderNewSingleRequest { + + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("client_order_id") + private String clientOrderId = null; + @SerializedName("symbol_id_exchange") + private String symbolIdExchange = null; + @SerializedName("symbol_id_coinapi") + private String symbolIdCoinapi = null; + @SerializedName("amount_order") + private BigDecimal amountOrder = null; + @SerializedName("price") + private BigDecimal price = null; + @SerializedName("side") + private OrdSide side = null; + @SerializedName("order_type") + private OrdType orderType = null; + @SerializedName("time_in_force") + private TimeInForce timeInForce = null; + @SerializedName("expire_time") + private Date expireTime = null; + public enum List<ExecInstEnum> { + MAKER_OR_CANCEL, AUCTION_ONLY, INDICATION_OF_INTEREST, + }; + @SerializedName("exec_inst") + private List execInst = null; + + /** + * Exchange identifier used to identify the routing destination. + **/ + @ApiModelProperty(required = true, value = "Exchange identifier used to identify the routing destination.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + * The unique identifier of the order assigned by the client. + **/ + @ApiModelProperty(required = true, value = "The unique identifier of the order assigned by the client.") + public String getClientOrderId() { + return clientOrderId; + } + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + /** + * Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + **/ + @ApiModelProperty(value = "Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.") + public String getSymbolIdExchange() { + return symbolIdExchange; + } + public void setSymbolIdExchange(String symbolIdExchange) { + this.symbolIdExchange = symbolIdExchange; + } + + /** + * CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + **/ + @ApiModelProperty(value = "CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order.") + public String getSymbolIdCoinapi() { + return symbolIdCoinapi; + } + public void setSymbolIdCoinapi(String symbolIdCoinapi) { + this.symbolIdCoinapi = symbolIdCoinapi; + } + + /** + * Order quantity. + **/ + @ApiModelProperty(required = true, value = "Order quantity.") + public BigDecimal getAmountOrder() { + return amountOrder; + } + public void setAmountOrder(BigDecimal amountOrder) { + this.amountOrder = amountOrder; + } + + /** + * Order price. + **/ + @ApiModelProperty(required = true, value = "Order price.") + public BigDecimal getPrice() { + return price; + } + public void setPrice(BigDecimal price) { + this.price = price; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdSide getSide() { + return side; + } + public void setSide(OrdSide side) { + this.side = side; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public OrdType getOrderType() { + return orderType; + } + public void setOrderType(OrdType orderType) { + this.orderType = orderType; + } + + /** + **/ + @ApiModelProperty(required = true, value = "") + public TimeInForce getTimeInForce() { + return timeInForce; + } + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + /** + * Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + **/ + @ApiModelProperty(value = "Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`.") + public Date getExpireTime() { + return expireTime; + } + public void setExpireTime(Date expireTime) { + this.expireTime = expireTime; + } + + /** + * Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions + **/ + @ApiModelProperty(value = "Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions ") + public List getExecInst() { + return execInst; + } + public void setExecInst(List execInst) { + this.execInst = execInst; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderNewSingleRequest orderNewSingleRequest = (OrderNewSingleRequest) o; + return (this.exchangeId == null ? orderNewSingleRequest.exchangeId == null : this.exchangeId.equals(orderNewSingleRequest.exchangeId)) && + (this.clientOrderId == null ? orderNewSingleRequest.clientOrderId == null : this.clientOrderId.equals(orderNewSingleRequest.clientOrderId)) && + (this.symbolIdExchange == null ? orderNewSingleRequest.symbolIdExchange == null : this.symbolIdExchange.equals(orderNewSingleRequest.symbolIdExchange)) && + (this.symbolIdCoinapi == null ? orderNewSingleRequest.symbolIdCoinapi == null : this.symbolIdCoinapi.equals(orderNewSingleRequest.symbolIdCoinapi)) && + (this.amountOrder == null ? orderNewSingleRequest.amountOrder == null : this.amountOrder.equals(orderNewSingleRequest.amountOrder)) && + (this.price == null ? orderNewSingleRequest.price == null : this.price.equals(orderNewSingleRequest.price)) && + (this.side == null ? orderNewSingleRequest.side == null : this.side.equals(orderNewSingleRequest.side)) && + (this.orderType == null ? orderNewSingleRequest.orderType == null : this.orderType.equals(orderNewSingleRequest.orderType)) && + (this.timeInForce == null ? orderNewSingleRequest.timeInForce == null : this.timeInForce.equals(orderNewSingleRequest.timeInForce)) && + (this.expireTime == null ? orderNewSingleRequest.expireTime == null : this.expireTime.equals(orderNewSingleRequest.expireTime)) && + (this.execInst == null ? orderNewSingleRequest.execInst == null : this.execInst.equals(orderNewSingleRequest.execInst)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.clientOrderId == null ? 0: this.clientOrderId.hashCode()); + result = 31 * result + (this.symbolIdExchange == null ? 0: this.symbolIdExchange.hashCode()); + result = 31 * result + (this.symbolIdCoinapi == null ? 0: this.symbolIdCoinapi.hashCode()); + result = 31 * result + (this.amountOrder == null ? 0: this.amountOrder.hashCode()); + result = 31 * result + (this.price == null ? 0: this.price.hashCode()); + result = 31 * result + (this.side == null ? 0: this.side.hashCode()); + result = 31 * result + (this.orderType == null ? 0: this.orderType.hashCode()); + result = 31 * result + (this.timeInForce == null ? 0: this.timeInForce.hashCode()); + result = 31 * result + (this.expireTime == null ? 0: this.expireTime.hashCode()); + result = 31 * result + (this.execInst == null ? 0: this.execInst.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderNewSingleRequest {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" clientOrderId: ").append(clientOrderId).append("\n"); + sb.append(" symbolIdExchange: ").append(symbolIdExchange).append("\n"); + sb.append(" symbolIdCoinapi: ").append(symbolIdCoinapi).append("\n"); + sb.append(" amountOrder: ").append(amountOrder).append("\n"); + sb.append(" price: ").append(price).append("\n"); + sb.append(" side: ").append(side).append("\n"); + sb.append(" orderType: ").append(orderType).append("\n"); + sb.append(" timeInForce: ").append(timeInForce).append("\n"); + sb.append(" expireTime: ").append(expireTime).append("\n"); + sb.append(" execInst: ").append(execInst).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Position.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Position.java new file mode 100644 index 0000000000..656c389aa7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/Position.java @@ -0,0 +1,81 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.util.*; +import org.openapitools.client.model.PositionData; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class Position { + + @SerializedName("exchange_id") + private String exchangeId = null; + @SerializedName("data") + private List data = null; + + /** + * Exchange identifier used to identify the routing destination. + **/ + @ApiModelProperty(value = "Exchange identifier used to identify the routing destination.") + public String getExchangeId() { + return exchangeId; + } + public void setExchangeId(String exchangeId) { + this.exchangeId = exchangeId; + } + + /** + **/ + @ApiModelProperty(value = "") + public List getData() { + return data; + } + public void setData(List data) { + this.data = data; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Position position = (Position) o; + return (this.exchangeId == null ? position.exchangeId == null : this.exchangeId.equals(position.exchangeId)) && + (this.data == null ? position.data == null : this.data.equals(position.data)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.exchangeId == null ? 0: this.exchangeId.hashCode()); + result = 31 * result + (this.data == null ? 0: this.data.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Position {\n"); + + sb.append(" exchangeId: ").append(exchangeId).append("\n"); + sb.append(" data: ").append(data).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/PositionData.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/PositionData.java new file mode 100644 index 0000000000..c7bd37dc81 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/PositionData.java @@ -0,0 +1,211 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import org.openapitools.client.model.OrdSide; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * The Position object. + **/ +@ApiModel(description = "The Position object.") +public class PositionData { + + @SerializedName("symbol_id_exchange") + private String symbolIdExchange = null; + @SerializedName("symbol_id_coinapi") + private String symbolIdCoinapi = null; + @SerializedName("avg_entry_price") + private BigDecimal avgEntryPrice = null; + @SerializedName("quantity") + private BigDecimal quantity = null; + @SerializedName("side") + private OrdSide side = null; + @SerializedName("unrealized_pnl") + private BigDecimal unrealizedPnl = null; + @SerializedName("leverage") + private BigDecimal leverage = null; + @SerializedName("cross_margin") + private Boolean crossMargin = null; + @SerializedName("liquidation_price") + private BigDecimal liquidationPrice = null; + @SerializedName("raw_data") + private Object rawData = null; + + /** + * Exchange symbol. + **/ + @ApiModelProperty(value = "Exchange symbol.") + public String getSymbolIdExchange() { + return symbolIdExchange; + } + public void setSymbolIdExchange(String symbolIdExchange) { + this.symbolIdExchange = symbolIdExchange; + } + + /** + * CoinAPI symbol. + **/ + @ApiModelProperty(value = "CoinAPI symbol.") + public String getSymbolIdCoinapi() { + return symbolIdCoinapi; + } + public void setSymbolIdCoinapi(String symbolIdCoinapi) { + this.symbolIdCoinapi = symbolIdCoinapi; + } + + /** + * Calculated average price of all fills on this position. + **/ + @ApiModelProperty(value = "Calculated average price of all fills on this position.") + public BigDecimal getAvgEntryPrice() { + return avgEntryPrice; + } + public void setAvgEntryPrice(BigDecimal avgEntryPrice) { + this.avgEntryPrice = avgEntryPrice; + } + + /** + * The current position quantity. + **/ + @ApiModelProperty(value = "The current position quantity.") + public BigDecimal getQuantity() { + return quantity; + } + public void setQuantity(BigDecimal quantity) { + this.quantity = quantity; + } + + /** + **/ + @ApiModelProperty(value = "") + public OrdSide getSide() { + return side; + } + public void setSide(OrdSide side) { + this.side = side; + } + + /** + * Unrealised profit or loss (PNL) of this position. + **/ + @ApiModelProperty(value = "Unrealised profit or loss (PNL) of this position.") + public BigDecimal getUnrealizedPnl() { + return unrealizedPnl; + } + public void setUnrealizedPnl(BigDecimal unrealizedPnl) { + this.unrealizedPnl = unrealizedPnl; + } + + /** + * Leverage for this position reported by the exchange. + **/ + @ApiModelProperty(value = "Leverage for this position reported by the exchange.") + public BigDecimal getLeverage() { + return leverage; + } + public void setLeverage(BigDecimal leverage) { + this.leverage = leverage; + } + + /** + * Is cross margin mode enable for this position? + **/ + @ApiModelProperty(value = "Is cross margin mode enable for this position?") + public Boolean getCrossMargin() { + return crossMargin; + } + public void setCrossMargin(Boolean crossMargin) { + this.crossMargin = crossMargin; + } + + /** + * Liquidation price. If mark price will reach this value, the position will be liquidated. + **/ + @ApiModelProperty(value = "Liquidation price. If mark price will reach this value, the position will be liquidated.") + public BigDecimal getLiquidationPrice() { + return liquidationPrice; + } + public void setLiquidationPrice(BigDecimal liquidationPrice) { + this.liquidationPrice = liquidationPrice; + } + + /** + **/ + @ApiModelProperty(value = "") + public Object getRawData() { + return rawData; + } + public void setRawData(Object rawData) { + this.rawData = rawData; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PositionData positionData = (PositionData) o; + return (this.symbolIdExchange == null ? positionData.symbolIdExchange == null : this.symbolIdExchange.equals(positionData.symbolIdExchange)) && + (this.symbolIdCoinapi == null ? positionData.symbolIdCoinapi == null : this.symbolIdCoinapi.equals(positionData.symbolIdCoinapi)) && + (this.avgEntryPrice == null ? positionData.avgEntryPrice == null : this.avgEntryPrice.equals(positionData.avgEntryPrice)) && + (this.quantity == null ? positionData.quantity == null : this.quantity.equals(positionData.quantity)) && + (this.side == null ? positionData.side == null : this.side.equals(positionData.side)) && + (this.unrealizedPnl == null ? positionData.unrealizedPnl == null : this.unrealizedPnl.equals(positionData.unrealizedPnl)) && + (this.leverage == null ? positionData.leverage == null : this.leverage.equals(positionData.leverage)) && + (this.crossMargin == null ? positionData.crossMargin == null : this.crossMargin.equals(positionData.crossMargin)) && + (this.liquidationPrice == null ? positionData.liquidationPrice == null : this.liquidationPrice.equals(positionData.liquidationPrice)) && + (this.rawData == null ? positionData.rawData == null : this.rawData.equals(positionData.rawData)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.symbolIdExchange == null ? 0: this.symbolIdExchange.hashCode()); + result = 31 * result + (this.symbolIdCoinapi == null ? 0: this.symbolIdCoinapi.hashCode()); + result = 31 * result + (this.avgEntryPrice == null ? 0: this.avgEntryPrice.hashCode()); + result = 31 * result + (this.quantity == null ? 0: this.quantity.hashCode()); + result = 31 * result + (this.side == null ? 0: this.side.hashCode()); + result = 31 * result + (this.unrealizedPnl == null ? 0: this.unrealizedPnl.hashCode()); + result = 31 * result + (this.leverage == null ? 0: this.leverage.hashCode()); + result = 31 * result + (this.crossMargin == null ? 0: this.crossMargin.hashCode()); + result = 31 * result + (this.liquidationPrice == null ? 0: this.liquidationPrice.hashCode()); + result = 31 * result + (this.rawData == null ? 0: this.rawData.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PositionData {\n"); + + sb.append(" symbolIdExchange: ").append(symbolIdExchange).append("\n"); + sb.append(" symbolIdCoinapi: ").append(symbolIdCoinapi).append("\n"); + sb.append(" avgEntryPrice: ").append(avgEntryPrice).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" side: ").append(side).append("\n"); + sb.append(" unrealizedPnl: ").append(unrealizedPnl).append("\n"); + sb.append(" leverage: ").append(leverage).append("\n"); + sb.append(" crossMargin: ").append(crossMargin).append("\n"); + sb.append(" liquidationPrice: ").append(liquidationPrice).append("\n"); + sb.append(" rawData: ").append(rawData).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/RejectReason.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/RejectReason.java new file mode 100644 index 0000000000..42549c5c9e --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/RejectReason.java @@ -0,0 +1,52 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Cause of rejection. + **/ +@ApiModel(description = "Cause of rejection.") +public class RejectReason { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RejectReason rejectReason = (RejectReason) o; + return true; + } + + @Override + public int hashCode() { + int result = 17; + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RejectReason {\n"); + + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/TimeInForce.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/TimeInForce.java new file mode 100644 index 0000000000..e6f2855a46 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/TimeInForce.java @@ -0,0 +1,52 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +/** + * Order time in force options are documented in the separate section: <a href=\"#ems-order-params-tif\">EMS / Starter Guide / Order parameters / Time in force</a> + **/ +@ApiModel(description = "Order time in force options are documented in the separate section: EMS / Starter Guide / Order parameters / Time in force ") +public class TimeInForce { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TimeInForce timeInForce = (TimeInForce) o; + return true; + } + + @Override + public int hashCode() { + int result = 17; + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TimeInForce {\n"); + + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/ValidationError.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/ValidationError.java new file mode 100644 index 0000000000..39ed44a6f6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/model/ValidationError.java @@ -0,0 +1,124 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.math.BigDecimal; +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + +@ApiModel(description = "") +public class ValidationError { + + @SerializedName("type") + private String type = null; + @SerializedName("title") + private String title = null; + @SerializedName("status") + private BigDecimal status = null; + @SerializedName("traceId") + private String traceId = null; + @SerializedName("errors") + private String errors = null; + + /** + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + + /** + **/ + @ApiModelProperty(value = "") + public BigDecimal getStatus() { + return status; + } + public void setStatus(BigDecimal status) { + this.status = status; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getTraceId() { + return traceId; + } + public void setTraceId(String traceId) { + this.traceId = traceId; + } + + /** + **/ + @ApiModelProperty(value = "") + public String getErrors() { + return errors; + } + public void setErrors(String errors) { + this.errors = errors; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ValidationError validationError = (ValidationError) o; + return (this.type == null ? validationError.type == null : this.type.equals(validationError.type)) && + (this.title == null ? validationError.title == null : this.title.equals(validationError.title)) && + (this.status == null ? validationError.status == null : this.status.equals(validationError.status)) && + (this.traceId == null ? validationError.traceId == null : this.traceId.equals(validationError.traceId)) && + (this.errors == null ? validationError.errors == null : this.errors.equals(validationError.errors)); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (this.type == null ? 0: this.type.hashCode()); + result = 31 * result + (this.title == null ? 0: this.title.hashCode()); + result = 31 * result + (this.status == null ? 0: this.status.hashCode()); + result = 31 * result + (this.traceId == null ? 0: this.traceId.hashCode()); + result = 31 * result + (this.errors == null ? 0: this.errors.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ValidationError {\n"); + + sb.append(" type: ").append(type).append("\n"); + sb.append(" title: ").append(title).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" traceId: ").append(traceId).append("\n"); + sb.append(" errors: ").append(errors).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/DeleteRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/DeleteRequest.java new file mode 100644 index 0000000000..7d030cf37a --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/DeleteRequest.java @@ -0,0 +1,104 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.request; + +import com.android.volley.AuthFailureError; +import com.android.volley.NetworkResponse; +import com.android.volley.Request; +import com.android.volley.Response; +import com.android.volley.VolleyLog; +import com.android.volley.toolbox.HttpHeaderParser; + +import org.apache.http.HttpEntity; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class DeleteRequest extends Request { + + HttpEntity entity; + + private final Response.Listener mListener; + + String contentType; + Map apiHeaders; + public DeleteRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.DELETE, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); + } + + return headers; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/GetRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/GetRequest.java new file mode 100644 index 0000000000..03a0090ac6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/GetRequest.java @@ -0,0 +1,51 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.request; + +import com.android.volley.AuthFailureError; +import com.android.volley.Response; +import com.android.volley.toolbox.StringRequest; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class GetRequest extends StringRequest{ + Map apiHeaders; + String contentType; + + public GetRequest(String url, Map apiHeaders, String contentType, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.GET, url, listener, errorListener); + this.apiHeaders = apiHeaders; + this.contentType = contentType; + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); + } + + return headers; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PatchRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PatchRequest.java new file mode 100644 index 0000000000..f66f16319e --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PatchRequest.java @@ -0,0 +1,104 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.request; + +import com.android.volley.AuthFailureError; +import com.android.volley.NetworkResponse; +import com.android.volley.Request; +import com.android.volley.Response; +import com.android.volley.VolleyLog; +import com.android.volley.toolbox.HttpHeaderParser; + +import org.apache.http.HttpEntity; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class PatchRequest extends Request { + + HttpEntity entity; + + private final Response.Listener mListener; + + String contentType; + Map apiHeaders; + public PatchRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PATCH, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); + } + + return headers; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PostRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PostRequest.java new file mode 100644 index 0000000000..0a77a51ad3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PostRequest.java @@ -0,0 +1,104 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.request; + +import com.android.volley.AuthFailureError; +import com.android.volley.NetworkResponse; +import com.android.volley.Request; +import com.android.volley.Response; +import com.android.volley.VolleyLog; +import com.android.volley.toolbox.HttpHeaderParser; + +import org.apache.http.HttpEntity; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class PostRequest extends Request { + + HttpEntity entity; + + private final Response.Listener mListener; + + String contentType; + Map apiHeaders; + public PostRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.POST, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); + } + + return headers; + } +} diff --git a/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PutRequest.java b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PutRequest.java new file mode 100644 index 0000000000..7fa4f76e3f --- /dev/null +++ b/ems-cloud-mgmt-sdk/android/src/main/java/org/openapitools/client/request/PutRequest.java @@ -0,0 +1,104 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.request; + +import com.android.volley.AuthFailureError; +import com.android.volley.NetworkResponse; +import com.android.volley.Request; +import com.android.volley.Response; +import com.android.volley.VolleyLog; +import com.android.volley.toolbox.HttpHeaderParser; + +import org.apache.http.HttpEntity; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class PutRequest extends Request { + + HttpEntity entity; + + private final Response.Listener mListener; + + String contentType; + Map apiHeaders; + public PutRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PUT, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); + } + + return headers; + } +} diff --git a/ems-cloud-mgmt-sdk/apex/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/apex/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/apex/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/apex/.openapi-generator/FILES new file mode 100644 index 0000000000..a740affaee --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/.openapi-generator/FILES @@ -0,0 +1,93 @@ +.openapi-generator-ignore +README.md +config/project-scratch-def.json +force-app/main/default/classes/OAS.cls +force-app/main/default/classes/OAS.cls-meta.xml +force-app/main/default/classes/OASBalance.cls +force-app/main/default/classes/OASBalance.cls-meta.xml +force-app/main/default/classes/OASBalanceData.cls +force-app/main/default/classes/OASBalanceData.cls-meta.xml +force-app/main/default/classes/OASBalanceDataTest.cls +force-app/main/default/classes/OASBalanceDataTest.cls-meta.xml +force-app/main/default/classes/OASBalanceTest.cls +force-app/main/default/classes/OASBalanceTest.cls-meta.xml +force-app/main/default/classes/OASBalancesApi.cls +force-app/main/default/classes/OASBalancesApi.cls-meta.xml +force-app/main/default/classes/OASBalancesApiTest.cls +force-app/main/default/classes/OASBalancesApiTest.cls-meta.xml +force-app/main/default/classes/OASClient.cls +force-app/main/default/classes/OASClient.cls-meta.xml +force-app/main/default/classes/OASFills.cls +force-app/main/default/classes/OASFills.cls-meta.xml +force-app/main/default/classes/OASFillsTest.cls +force-app/main/default/classes/OASFillsTest.cls-meta.xml +force-app/main/default/classes/OASMessageReject.cls +force-app/main/default/classes/OASMessageReject.cls-meta.xml +force-app/main/default/classes/OASMessageRejectTest.cls +force-app/main/default/classes/OASMessageRejectTest.cls-meta.xml +force-app/main/default/classes/OASOrdSide.cls +force-app/main/default/classes/OASOrdSide.cls-meta.xml +force-app/main/default/classes/OASOrdSideTest.cls +force-app/main/default/classes/OASOrdSideTest.cls-meta.xml +force-app/main/default/classes/OASOrdStatus.cls +force-app/main/default/classes/OASOrdStatus.cls-meta.xml +force-app/main/default/classes/OASOrdStatusTest.cls +force-app/main/default/classes/OASOrdStatusTest.cls-meta.xml +force-app/main/default/classes/OASOrdType.cls +force-app/main/default/classes/OASOrdType.cls-meta.xml +force-app/main/default/classes/OASOrdTypeTest.cls +force-app/main/default/classes/OASOrdTypeTest.cls-meta.xml +force-app/main/default/classes/OASOrderCancelAllRequest.cls +force-app/main/default/classes/OASOrderCancelAllRequest.cls-meta.xml +force-app/main/default/classes/OASOrderCancelAllRequestTest.cls +force-app/main/default/classes/OASOrderCancelAllRequestTest.cls-meta.xml +force-app/main/default/classes/OASOrderCancelSingleRequest.cls +force-app/main/default/classes/OASOrderCancelSingleRequest.cls-meta.xml +force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls +force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls-meta.xml +force-app/main/default/classes/OASOrderExecutionReport.cls +force-app/main/default/classes/OASOrderExecutionReport.cls-meta.xml +force-app/main/default/classes/OASOrderExecutionReportAllOf.cls +force-app/main/default/classes/OASOrderExecutionReportAllOf.cls-meta.xml +force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls +force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls-meta.xml +force-app/main/default/classes/OASOrderExecutionReportTest.cls +force-app/main/default/classes/OASOrderExecutionReportTest.cls-meta.xml +force-app/main/default/classes/OASOrderNewSingleRequest.cls +force-app/main/default/classes/OASOrderNewSingleRequest.cls-meta.xml +force-app/main/default/classes/OASOrderNewSingleRequestTest.cls +force-app/main/default/classes/OASOrderNewSingleRequestTest.cls-meta.xml +force-app/main/default/classes/OASOrdersApi.cls +force-app/main/default/classes/OASOrdersApi.cls-meta.xml +force-app/main/default/classes/OASOrdersApiTest.cls +force-app/main/default/classes/OASOrdersApiTest.cls-meta.xml +force-app/main/default/classes/OASPosition.cls +force-app/main/default/classes/OASPosition.cls-meta.xml +force-app/main/default/classes/OASPositionData.cls +force-app/main/default/classes/OASPositionData.cls-meta.xml +force-app/main/default/classes/OASPositionDataTest.cls +force-app/main/default/classes/OASPositionDataTest.cls-meta.xml +force-app/main/default/classes/OASPositionTest.cls +force-app/main/default/classes/OASPositionTest.cls-meta.xml +force-app/main/default/classes/OASPositionsApi.cls +force-app/main/default/classes/OASPositionsApi.cls-meta.xml +force-app/main/default/classes/OASPositionsApiTest.cls +force-app/main/default/classes/OASPositionsApiTest.cls-meta.xml +force-app/main/default/classes/OASRejectReason.cls +force-app/main/default/classes/OASRejectReason.cls-meta.xml +force-app/main/default/classes/OASRejectReasonTest.cls +force-app/main/default/classes/OASRejectReasonTest.cls-meta.xml +force-app/main/default/classes/OASResponseMock.cls +force-app/main/default/classes/OASResponseMock.cls-meta.xml +force-app/main/default/classes/OASTest.cls +force-app/main/default/classes/OASTest.cls-meta.xml +force-app/main/default/classes/OASTimeInForce.cls +force-app/main/default/classes/OASTimeInForce.cls-meta.xml +force-app/main/default/classes/OASTimeInForceTest.cls +force-app/main/default/classes/OASTimeInForceTest.cls-meta.xml +force-app/main/default/classes/OASValidationError.cls +force-app/main/default/classes/OASValidationError.cls-meta.xml +force-app/main/default/classes/OASValidationErrorTest.cls +force-app/main/default/classes/OASValidationErrorTest.cls-meta.xml +force-app/main/default/namedCredentials/EMS__REST_API.namedCredential-meta.xml +sfdx-project.json diff --git a/ems-cloud-mgmt-sdk/apex/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/apex/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/README.md b/ems-cloud-mgmt-sdk/apex/README.md new file mode 100644 index 0000000000..74405c1f7a --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/README.md @@ -0,0 +1,104 @@ +# EMS - REST API API Client + + +This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + +## Requirements + +- [Salesforce DX](https://www.salesforce.com/products/platform/products/salesforce-dx/) + +If everything is set correctly: + +- Running `sfdx version` in a command prompt should output something like: + + ```bash + sfdx-cli/5.7.5-05549de (darwin-amd64) go1.7.5 sfdxstable + ``` + +## Installation + +1. Copy the output into your Salesforce DX folder - or alternatively deploy the output directly into the workspace. +2. Deploy the code via Salesforce DX to your Scratch Org + + ```bash + sfdx force:source:push + ``` + +3. If the API needs authentication update the Named Credential in Setup. +4. Run your Apex tests using + + ```bash + sfdx sfdx force:apex:test:run + ``` + +5. Retrieve the job id from the console and check the test results. + + ```bash + sfdx force:apex:test:report -i theJobId + ``` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Apex code: + +```java +OASBalancesApi api = new OASBalancesApi(); + +Map params = new Map{ + 'exchangeId' => KRAKEN +}; + +try { + // cross your fingers + List result = api.v1BalancesGet(params); + System.debug(result); +} catch (OAS.ApiException e) { + // ...handle your exceptions +} +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*OASBalancesApi* | [**v1BalancesGet**](OASBalancesApi.md#v1BalancesGet) | **GET** /v1/balances | Get balances +*OASOrdersApi* | [**v1OrdersCancelAllPost**](OASOrdersApi.md#v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +*OASOrdersApi* | [**v1OrdersCancelPost**](OASOrdersApi.md#v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +*OASOrdersApi* | [**v1OrdersGet**](OASOrdersApi.md#v1OrdersGet) | **GET** /v1/orders | Get open orders +*OASOrdersApi* | [**v1OrdersPost**](OASOrdersApi.md#v1OrdersPost) | **POST** /v1/orders | Send new order +*OASOrdersApi* | [**v1OrdersStatusClientOrderIdGet**](OASOrdersApi.md#v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report +*OASPositionsApi* | [**v1PositionsGet**](OASPositionsApi.md#v1PositionsGet) | **GET** /v1/positions | Get open positions + + +## Documentation for Models + + - [OASBalance](OASBalance.md) + - [OASBalanceData](OASBalanceData.md) + - [OASFills](OASFills.md) + - [OASMessageReject](OASMessageReject.md) + - [OASOrdSide](OASOrdSide.md) + - [OASOrdStatus](OASOrdStatus.md) + - [OASOrdType](OASOrdType.md) + - [OASOrderCancelAllRequest](OASOrderCancelAllRequest.md) + - [OASOrderCancelSingleRequest](OASOrderCancelSingleRequest.md) + - [OASOrderExecutionReport](OASOrderExecutionReport.md) + - [OASOrderExecutionReportAllOf](OASOrderExecutionReportAllOf.md) + - [OASOrderNewSingleRequest](OASOrderNewSingleRequest.md) + - [OASPosition](OASPosition.md) + - [OASPositionData](OASPositionData.md) + - [OASRejectReason](OASRejectReason.md) + - [OASTimeInForce](OASTimeInForce.md) + - [OASValidationError](OASValidationError.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. +Authentication schemes defined for the API: + +## Author + +support@coinapi.io + diff --git a/ems-cloud-mgmt-sdk/apex/config/project-scratch-def.json b/ems-cloud-mgmt-sdk/apex/config/project-scratch-def.json new file mode 100644 index 0000000000..36aace5526 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/config/project-scratch-def.json @@ -0,0 +1,8 @@ +{ + "orgName": "muenzpraeger - René Winkelmeyer", + "edition": "Developer", + "orgPreferences": { + "enabled": ["S1DesktopEnabled"], + "disabled": ["S1EncryptedStoragePref2"] + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls new file mode 100644 index 0000000000..f3a630a385 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls @@ -0,0 +1,311 @@ +public class OAS { + private static final String HEADER_CONTENT_TYPE = 'Content-Type'; + private static final String HEADER_ACCEPT = 'Accept'; + private static final String HEADER_ACCEPT_DELIMITER = ','; + private static final Map DELIMITERS = new Map { + 'csv' => ',', + 'ssv' => ' ', + 'tsv' => '\t', + 'pipes' => '|' + }; + + public class Param { + private String name, value; + + public Param(String name, String value) { + this.name = name; + this.value = value; + } + + public override String toString() { + return EncodingUtil.urlEncode(name, 'UTF-8') + '=' + + EncodingUtil.urlEncode(value, 'UTF-8'); + } + } + + public interface Authentication { + void apply(Map headers, List query); + } + + public interface MappedProperties { + Map getPropertyMappings(); + } + + public abstract class ApiKeyAuth implements Authentication { + protected final String paramName; + protected String key = ''; + + public void setApiKey(String key) { + this.key = key; + } + + @TestVisible + private String getApiKey() { + return key; + } + } + + public class ApiKeyQueryAuth extends ApiKeyAuth { + public ApiKeyQueryAuth(String paramName) { + this.paramName = paramName; + } + + public void apply(Map headers, List query) { + query.add(new Param(paramName, key)); + } + } + + public class ApiKeyHeaderAuth extends ApiKeyAuth { + public ApiKeyHeaderAuth(String paramName) { + this.paramName = paramName; + } + + public void apply(Map headers, List query) { + headers.put(paramName, key); + } + } + + + public class ApiException extends Exception { + private final Integer code; + private final String status; + private final Map headers; + private final String body; + + public ApiException(Integer code, String status, Map headers, String body) { + this('API returned HTTP ' + code + ': ' + status); + this.code = code; + this.status = status; + this.headers = headers; + this.body = body; + } + + public Integer getStatusCode() { + return code; + } + + public String getStatus() { + return status; + } + + public Map getHeaders() { + return headers; + } + + public String getBody() { + return body; + } + } + + public virtual class ApiClient { + protected String preferredContentType = 'application/json'; + protected String preferredAccept = 'application/json'; + protected final String basePath; + protected final String calloutName; + + @TestVisible + protected final Map authentications = new Map(); + + public virtual Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + public virtual void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new NoSuchElementException('No API key authentication configured!'); + } + + public List makeParams(String name, List values) { + List pairs = new List(); + for (Object value : new List(values)) { + pairs.add(new Param(name, String.valueOf(value))); + } + return pairs; + } + + public List makeParam(String name, List values, String format) { + List pairs = new List(); + if (values != null) { + String delimiter = DELIMITERS.get(format); + pairs.add(new Param(name, String.join(values, delimiter))); + } + return pairs; + } + + public List makeParam(String name, Object value) { + List pairs = new List(); + if (value != null) { + pairs.add(new Param(name, String.valueOf(value))); + } + return pairs; + } + + public virtual void assertNotNull(Object required, String parameterName) { + if (required == null) { + Exception e = new NullPointerException(); + e.setMessage('Argument cannot be null: ' + parameterName); + throw e; + } + } + + public virtual Object invoke( + String method, String path, Object body, List query, List form, + Map pathParams, Map headers, List accepts, + List contentTypes, List authMethods, Type returnType) { + + HttpResponse res = getResponse(method, path, body, query, form, pathParams, headers, + accepts, contentTypes, authMethods); + + Integer code = res.getStatusCode(); + Boolean isFailure = code / 100 != 2; + if (isFailure) { + throw new ApiException(code, res.getStatus(), getHeaders(res), res.getBody()); + } else if (returnType != null) { + return toReturnValue(res.getBody(), returnType, res.getHeader('Content-Type')); + } + return null; + } + + @TestVisible + protected virtual Map getHeaders(HttpResponse res) { + Map headers = new Map(); + List headerKeys = res.getHeaderKeys(); + for (String headerKey : headerKeys) { + headers.put(headerKey, res.getHeader(headerKey)); + } + return headers; + } + + @TestVisible + protected virtual Object toReturnValue(String body, Type returnType, String contentType) { + if (contentType.contains('application/json')) { + Object o = returnType.newInstance(); + if (o instanceof MappedProperties) { + Map propertyMappings = ((MappedProperties) o).getPropertyMappings(); + for (String baseName : propertyMappings.keySet()) { + body = body.replaceAll('"' + baseName + '"\\s*:', + '"' + propertyMappings.get(baseName) + '":'); + } + } + JsonParser parser = Json.createParser(body); + parser.nextToken(); + return parser.readValueAs(returnType); + } + return body; + } + + @TestVisible + protected virtual HttpResponse getResponse( + String method, String path, Object body, List query, List form, + Map pathParams, Map headers, List accepts, + List contentTypes, List authMethods) { + + HttpRequest req = new HttpRequest(); + applyAuthentication(authMethods, headers, query); + req.setMethod(method); + req.setEndpoint(toEndpoint(path, pathParams, query)); + String contentType = setContentTypeHeader(contentTypes, headers); + setAcceptHeader(accepts, headers); + setHeaders(req, headers); + + if (method != 'GET') { + req.setBody(toBody(contentType, body, form)); + } + + return new Http().send(req); + } + + @TestVisible + protected virtual void setHeaders(HttpRequest req, Map headers) { + for (String headerName : headers.keySet()) { + req.setHeader(headerName, String.valueOf(headers.get(headerName))); + } + } + + @TestVisible + protected virtual String toBody(String contentType, Object body, List form) { + if (contentType.contains('application/x-www-form-urlencoded')) { + return paramsToString(form); + } else if (contentType.contains('application/json')) { + return Json.serialize(body); + } + return String.valueOf(body); + } + + @TestVisible + protected virtual String setContentTypeHeader(List contentTypes, + Map headers) { + if (contentTypes.isEmpty()) { + headers.put(HEADER_CONTENT_TYPE, preferredContentType); + return preferredContentType; + } + for (String contentType : contentTypes) { + if (preferredContentType == contentType) { + headers.put(HEADER_CONTENT_TYPE, contentType); + return contentType; + } + } + String contentType = contentTypes.get(0); + headers.put(HEADER_CONTENT_TYPE, contentType); + return contentType; + } + + @TestVisible + protected virtual void setAcceptHeader(List accepts, Map headers) { + for (String accept : accepts) { + if (preferredAccept == accept) { + headers.put(HEADER_ACCEPT, accept); + return; + } + } + if (!accepts.isEmpty()) { + headers.put(HEADER_ACCEPT, String.join(accepts, HEADER_ACCEPT_DELIMITER)); + } + } + + @TestVisible + protected virtual void applyAuthentication(List names, Map headers, + List query) { + // TODO Check auth methods + } + + @TestVisible + protected virtual List getAuthMethods(List names) { + List authMethods = new List(); + for (String name : names) { + authMethods.add(authentications.get(name)); + } + return authMethods; + } + + @TestVisible + protected virtual String toPath(String path, Map params) { + String formatted = path; + for (String key : params.keySet()) { + formatted = formatted.replace('{' + key + '}', String.valueOf(params.get(key))); + } + return formatted; + } + + @TestVisible + protected virtual String toEndpoint(String path, Map params, + List queryParams) { + String query = '?' + paramsToString(queryParams); + return 'callout:' + calloutName + toPath(path, params) + query.removeEnd('?'); + } + + @TestVisible + protected virtual String paramsToString(List params) { + String s = ''; + for (Param p : params) { + s += '&' + p; + } + return s.removeStart('&'); + } + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OAS.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls new file mode 100644 index 0000000000..cb92baa168 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls @@ -0,0 +1,64 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASBalance + */ +public class OASBalance implements OAS.MappedProperties { + /** + * Exchange identifier used to identify the routing destination. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * Get data + * @return data + */ + public List data { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public OASBalance() { + data = new List(); + } + + public static OASBalance getExample() { + OASBalance balance = new OASBalance(); + balance.exchangeId = 'KRAKEN'; + balance.data = new List{OASBalanceData.getExample()}; + return balance; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASBalance) { + OASBalance balance = (OASBalance) obj; + return this.exchangeId == balance.exchangeId + && this.data == balance.data; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (data == null ? 0 : System.hashCode(data)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalance.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls new file mode 100644 index 0000000000..2c76dbd195 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls @@ -0,0 +1,159 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASBalanceData + */ +public class OASBalanceData implements OAS.MappedProperties { + /** + * Exchange currency code. + * @return assetIdExchange + */ + public String assetIdExchange { get; set; } + + /** + * CoinAPI currency code. + * @return assetIdCoinapi + */ + public String assetIdCoinapi { get; set; } + + /** + * Value of the current total currency balance on the exchange. + * @return balance + */ + public Double balance { get; set; } + + /** + * Value of the current available currency balance on the exchange that can be used as collateral. + * @return available + */ + public Double available { get; set; } + + /** + * Value of the current locked currency balance by the exchange. + * @return locked + */ + public Double locked { get; set; } + + /** + * Source of the last modification.\n + */ + public enum LastUpdatedByEnum { + INITIALIZATION, + BALANCE_MANAGER, + EXCHANGE + } + + /** + * Source of the last modification.\n + * @return lastUpdatedBy + */ + public LastUpdatedByEnum lastUpdatedBy { get; set; } + + /** + * Current exchange rate to the USD for the single unit of the currency.\n + * @return rateUsd + */ + public Double rateUsd { get; set; } + + /** + * Value of the current total traded. + * @return traded + */ + public Double traded { get; set; } + + private static final Map propertyMappings = new Map{ + 'asset_id_exchange' => 'assetIdExchange', + 'asset_id_coinapi' => 'assetIdCoinapi', + 'last_updated_by' => 'lastUpdatedBy', + 'rate_usd' => 'rateUsd' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'asset_id_exchange' => 'assetIdExchange', + 'asset_id_coinapi' => 'assetIdCoinapi', + 'last_updated_by' => 'lastUpdatedBy', + 'rate_usd' => 'rateUsd' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'asset_id_exchange' => 'assetIdExchange', + 'asset_id_coinapi' => 'assetIdCoinapi', + 'last_updated_by' => 'lastUpdatedBy', + 'rate_usd' => 'rateUsd' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'asset_id_exchange' => 'assetIdExchange', + 'asset_id_coinapi' => 'assetIdCoinapi', + 'last_updated_by' => 'lastUpdatedBy', + 'rate_usd' => 'rateUsd' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASBalanceData getExample() { + OASBalanceData balanceData = new OASBalanceData(); + balanceData.assetIdExchange = 'XBT'; + balanceData.assetIdCoinapi = 'BTC'; + balanceData.balance = 0.00134444; + balanceData.available = 0.00134444; + balanceData.locked = 0.0; + balanceData.lastUpdatedBy = LastUpdatedByEnum.EXCHANGE; + balanceData.rateUsd = 1355.12; + balanceData.traded = 0.007; + return balanceData; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASBalanceData) { + OASBalanceData balanceData = (OASBalanceData) obj; + return this.assetIdExchange == balanceData.assetIdExchange + && this.assetIdCoinapi == balanceData.assetIdCoinapi + && this.balance == balanceData.balance + && this.available == balanceData.available + && this.locked == balanceData.locked + && this.lastUpdatedBy == balanceData.lastUpdatedBy + && this.rateUsd == balanceData.rateUsd + && this.traded == balanceData.traded; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (assetIdExchange == null ? 0 : System.hashCode(assetIdExchange)); + hashCode = (17 * hashCode) + (assetIdCoinapi == null ? 0 : System.hashCode(assetIdCoinapi)); + hashCode = (17 * hashCode) + (balance == null ? 0 : System.hashCode(balance)); + hashCode = (17 * hashCode) + (available == null ? 0 : System.hashCode(available)); + hashCode = (17 * hashCode) + (locked == null ? 0 : System.hashCode(locked)); + hashCode = (17 * hashCode) + (lastUpdatedBy == null ? 0 : System.hashCode(lastUpdatedBy)); + hashCode = (17 * hashCode) + (rateUsd == null ? 0 : System.hashCode(rateUsd)); + hashCode = (17 * hashCode) + (traded == null ? 0 : System.hashCode(traded)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceData.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls new file mode 100644 index 0000000000..40531af243 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls @@ -0,0 +1,81 @@ +@isTest +private class OASBalanceDataTest { + @isTest + private static void equalsSameInstance() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = balanceData1; + OASBalanceData balanceData3 = new OASBalanceData(); + OASBalanceData balanceData4 = balanceData3; + + System.assert(balanceData1.equals(balanceData2)); + System.assert(balanceData2.equals(balanceData1)); + System.assert(balanceData1.equals(balanceData1)); + System.assert(balanceData3.equals(balanceData4)); + System.assert(balanceData4.equals(balanceData3)); + System.assert(balanceData3.equals(balanceData3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = OASBalanceData.getExample(); + OASBalanceData balanceData3 = new OASBalanceData(); + OASBalanceData balanceData4 = new OASBalanceData(); + + System.assert(balanceData1.equals(balanceData2)); + System.assert(balanceData2.equals(balanceData1)); + System.assert(balanceData3.equals(balanceData4)); + System.assert(balanceData4.equals(balanceData3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = new OASBalanceData(); + + System.assertEquals(false, balanceData1.equals('foo')); + System.assertEquals(false, balanceData2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = new OASBalanceData(); + OASBalanceData balanceData3; + + System.assertEquals(false, balanceData1.equals(balanceData3)); + System.assertEquals(false, balanceData2.equals(balanceData3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = new OASBalanceData(); + + System.assertEquals(balanceData1.hashCode(), balanceData1.hashCode()); + System.assertEquals(balanceData2.hashCode(), balanceData2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASBalanceData balanceData1 = OASBalanceData.getExample(); + OASBalanceData balanceData2 = OASBalanceData.getExample(); + OASBalanceData balanceData3 = new OASBalanceData(); + OASBalanceData balanceData4 = new OASBalanceData(); + + System.assert(balanceData1.equals(balanceData2)); + System.assert(balanceData3.equals(balanceData4)); + System.assertEquals(balanceData1.hashCode(), balanceData2.hashCode()); + System.assertEquals(balanceData3.hashCode(), balanceData4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASBalanceData balanceData = new OASBalanceData(); + Map x-property-mappings = balanceData.getx-property-mappings(); + System.assertEquals('assetIdExchange', x-property-mappings.get('asset_id_exchange')); + System.assertEquals('assetIdCoinapi', x-property-mappings.get('asset_id_coinapi')); + System.assertEquals('lastUpdatedBy', x-property-mappings.get('last_updated_by')); + System.assertEquals('rateUsd', x-property-mappings.get('rate_usd')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceDataTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls new file mode 100644 index 0000000000..6306f2e989 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls @@ -0,0 +1,85 @@ +@isTest +private class OASBalanceTest { + @isTest + private static void equalsSameInstance() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = balance1; + OASBalance balance3 = new OASBalance(); + OASBalance balance4 = balance3; + + System.assert(balance1.equals(balance2)); + System.assert(balance2.equals(balance1)); + System.assert(balance1.equals(balance1)); + System.assert(balance3.equals(balance4)); + System.assert(balance4.equals(balance3)); + System.assert(balance3.equals(balance3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = OASBalance.getExample(); + OASBalance balance3 = new OASBalance(); + OASBalance balance4 = new OASBalance(); + + System.assert(balance1.equals(balance2)); + System.assert(balance2.equals(balance1)); + System.assert(balance3.equals(balance4)); + System.assert(balance4.equals(balance3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = new OASBalance(); + + System.assertEquals(false, balance1.equals('foo')); + System.assertEquals(false, balance2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = new OASBalance(); + OASBalance balance3; + + System.assertEquals(false, balance1.equals(balance3)); + System.assertEquals(false, balance2.equals(balance3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = new OASBalance(); + + System.assertEquals(balance1.hashCode(), balance1.hashCode()); + System.assertEquals(balance2.hashCode(), balance2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASBalance balance1 = OASBalance.getExample(); + OASBalance balance2 = OASBalance.getExample(); + OASBalance balance3 = new OASBalance(); + OASBalance balance4 = new OASBalance(); + + System.assert(balance1.equals(balance2)); + System.assert(balance3.equals(balance4)); + System.assertEquals(balance1.hashCode(), balance2.hashCode()); + System.assertEquals(balance3.hashCode(), balance4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASBalance balance = new OASBalance(); + Map x-property-mappings = balance.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + } + + @isTest + private static void defaultValuesPopulated() { + OASBalance balance = new OASBalance(); + System.assertEquals(new List(), balance.data); + System.assertEquals(null, balance.exchangeId); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalanceTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls new file mode 100644 index 0000000000..9c3a003456 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls @@ -0,0 +1,54 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +public class OASBalancesApi { + OASClient client; + + public OASBalancesApi(OASClient client) { + this.client = client; + } + + public OASBalancesApi() { + this.client = new OASClient(); + } + + public OASClient getClient() { + return this.client; + } + + /** + * Get balances + * Get current currency balance from all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. (optional) + * @return List + * @throws OAS.ApiException if fails to make API call + */ + public List v1BalancesGet(Map params) { + List query = new List(); + + // cast query params to verify their expected type + query.addAll(client.makeParam('exchange_id', (String) params.get('exchangeId'))); + + List form = new List(); + + return (List) client.invoke( + 'GET', '/v1/balances', '', + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List(), + new List(), + List.class + ); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApi.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls new file mode 100644 index 0000000000..8475490b63 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls @@ -0,0 +1,34 @@ +@isTest +private class OASBalancesApiTest { + /** + * Get balances + * + * Get current currency balance from all or single exchange. + */ + @isTest + private static void v1BalancesGetTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'exchangeId' => KRAKEN + }; + + OASClient client; + OASBalancesApi api; + List response; + List expectedResponse; + String js = ''; + + api = new OASBalancesApi(new OASClient()); + + js = JSON.serialize(List.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = List.getExample(); + response = (List) api.v1BalancesGet(params); + System.assertEquals(expectedResponse, response); + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASBalancesApiTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls new file mode 100644 index 0000000000..fea1985721 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls @@ -0,0 +1,6 @@ +public class OASClient extends OAS.ApiClient { + public OASClient() { + basePath = 'https://ems-gateway-aws-eu-central-1-dev.coinapi.io'; + calloutName = 'EMS__REST_API'; + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASClient.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls new file mode 100644 index 0000000000..79fda6f68b --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls @@ -0,0 +1,69 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASFills + */ +public class OASFills implements OAS.MappedProperties { + /** + * Execution time. + * @return r_time + */ + public Date r_time { get; set; } + + /** + * Execution price. + * @return price + */ + public Double price { get; set; } + + /** + * Executed quantity. + * @return amount + */ + public Double amount { get; set; } + + private static final Map propertyMappings = new Map{ + 'time' => 'r_time' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASFills getExample() { + OASFills fills = new OASFills(); + fills.r_time = Date.getExample(); + fills.price = 10799.2; + fills.amount = 0.002; + return fills; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASFills) { + OASFills fills = (OASFills) obj; + return this.r_time == fills.r_time + && this.price == fills.price + && this.amount == fills.amount; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (r_time == null ? 0 : System.hashCode(r_time)); + hashCode = (17 * hashCode) + (price == null ? 0 : System.hashCode(price)); + hashCode = (17 * hashCode) + (amount == null ? 0 : System.hashCode(amount)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFills.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls new file mode 100644 index 0000000000..ad64c2760b --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls @@ -0,0 +1,78 @@ +@isTest +private class OASFillsTest { + @isTest + private static void equalsSameInstance() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = fills1; + OASFills fills3 = new OASFills(); + OASFills fills4 = fills3; + + System.assert(fills1.equals(fills2)); + System.assert(fills2.equals(fills1)); + System.assert(fills1.equals(fills1)); + System.assert(fills3.equals(fills4)); + System.assert(fills4.equals(fills3)); + System.assert(fills3.equals(fills3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = OASFills.getExample(); + OASFills fills3 = new OASFills(); + OASFills fills4 = new OASFills(); + + System.assert(fills1.equals(fills2)); + System.assert(fills2.equals(fills1)); + System.assert(fills3.equals(fills4)); + System.assert(fills4.equals(fills3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = new OASFills(); + + System.assertEquals(false, fills1.equals('foo')); + System.assertEquals(false, fills2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = new OASFills(); + OASFills fills3; + + System.assertEquals(false, fills1.equals(fills3)); + System.assertEquals(false, fills2.equals(fills3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = new OASFills(); + + System.assertEquals(fills1.hashCode(), fills1.hashCode()); + System.assertEquals(fills2.hashCode(), fills2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASFills fills1 = OASFills.getExample(); + OASFills fills2 = OASFills.getExample(); + OASFills fills3 = new OASFills(); + OASFills fills4 = new OASFills(); + + System.assert(fills1.equals(fills2)); + System.assert(fills3.equals(fills4)); + System.assertEquals(fills1.hashCode(), fills2.hashCode()); + System.assertEquals(fills3.hashCode(), fills4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASFills fills = new OASFills(); + Map x-property-mappings = fills.getx-property-mappings(); + System.assertEquals('r_time', x-property-mappings.get('time')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASFillsTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls new file mode 100644 index 0000000000..f063a6b054 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls @@ -0,0 +1,109 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASMessageReject + */ +public class OASMessageReject implements OAS.MappedProperties { + /** + * Message type, constant. + * @return type + */ + public String type { get; set; } + + /** + * Get rejectReason + * @return rejectReason + */ + public OASRejectReason rejectReason { get; set; } + + /** + * If the message related to exchange, then the identifier of the exchange will be provided. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * Message text. + * @return message + */ + public String message { get; set; } + + /** + * Value of rejected request, if available. + * @return rejectedMessage + */ + public String rejectedMessage { get; set; } + + private static final Map propertyMappings = new Map{ + 'reject_reason' => 'rejectReason', + 'exchange_id' => 'exchangeId', + 'rejected_message' => 'rejectedMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'reject_reason' => 'rejectReason', + 'exchange_id' => 'exchangeId', + 'rejected_message' => 'rejectedMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'reject_reason' => 'rejectReason', + 'exchange_id' => 'exchangeId', + 'rejected_message' => 'rejectedMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASMessageReject getExample() { + OASMessageReject messageReject = new OASMessageReject(); + messageReject.type = 'MESSAGE_REJECT'; + messageReject.rejectReason = OASRejectReason.getExample(); + messageReject.exchangeId = 'BINANCE'; + messageReject.message = 'Order with ID: BINANCE-7d8a-4888 not found'; + messageReject.rejectedMessage = '{"client_order_id":"BINANCE-7d8a-4888","exchange_id":"BINANCE","type":"ORDER_CANCEL_SINGLE_REQUEST"}'; + return messageReject; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASMessageReject) { + OASMessageReject messageReject = (OASMessageReject) obj; + return this.type == messageReject.type + && this.rejectReason == messageReject.rejectReason + && this.exchangeId == messageReject.exchangeId + && this.message == messageReject.message + && this.rejectedMessage == messageReject.rejectedMessage; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (type == null ? 0 : System.hashCode(type)); + hashCode = (17 * hashCode) + (rejectReason == null ? 0 : System.hashCode(rejectReason)); + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (message == null ? 0 : System.hashCode(message)); + hashCode = (17 * hashCode) + (rejectedMessage == null ? 0 : System.hashCode(rejectedMessage)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageReject.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls new file mode 100644 index 0000000000..43d12853c0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls @@ -0,0 +1,80 @@ +@isTest +private class OASMessageRejectTest { + @isTest + private static void equalsSameInstance() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = messageReject1; + OASMessageReject messageReject3 = new OASMessageReject(); + OASMessageReject messageReject4 = messageReject3; + + System.assert(messageReject1.equals(messageReject2)); + System.assert(messageReject2.equals(messageReject1)); + System.assert(messageReject1.equals(messageReject1)); + System.assert(messageReject3.equals(messageReject4)); + System.assert(messageReject4.equals(messageReject3)); + System.assert(messageReject3.equals(messageReject3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = OASMessageReject.getExample(); + OASMessageReject messageReject3 = new OASMessageReject(); + OASMessageReject messageReject4 = new OASMessageReject(); + + System.assert(messageReject1.equals(messageReject2)); + System.assert(messageReject2.equals(messageReject1)); + System.assert(messageReject3.equals(messageReject4)); + System.assert(messageReject4.equals(messageReject3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = new OASMessageReject(); + + System.assertEquals(false, messageReject1.equals('foo')); + System.assertEquals(false, messageReject2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = new OASMessageReject(); + OASMessageReject messageReject3; + + System.assertEquals(false, messageReject1.equals(messageReject3)); + System.assertEquals(false, messageReject2.equals(messageReject3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = new OASMessageReject(); + + System.assertEquals(messageReject1.hashCode(), messageReject1.hashCode()); + System.assertEquals(messageReject2.hashCode(), messageReject2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASMessageReject messageReject1 = OASMessageReject.getExample(); + OASMessageReject messageReject2 = OASMessageReject.getExample(); + OASMessageReject messageReject3 = new OASMessageReject(); + OASMessageReject messageReject4 = new OASMessageReject(); + + System.assert(messageReject1.equals(messageReject2)); + System.assert(messageReject3.equals(messageReject4)); + System.assertEquals(messageReject1.hashCode(), messageReject2.hashCode()); + System.assertEquals(messageReject3.hashCode(), messageReject4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASMessageReject messageReject = new OASMessageReject(); + Map x-property-mappings = messageReject.getx-property-mappings(); + System.assertEquals('rejectReason', x-property-mappings.get('reject_reason')); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + System.assertEquals('rejectedMessage', x-property-mappings.get('rejected_message')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASMessageRejectTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls new file mode 100644 index 0000000000..5dfb0a9877 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls @@ -0,0 +1,20 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Side of order.\n + */ +public enum OASOrdSide { + BUY, + SELL +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSide.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls new file mode 100644 index 0000000000..d35919bc81 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls @@ -0,0 +1,12 @@ +@isTest +private class OASOrdSideTest { + @isTest + private static void allowableValues() { + Set expected = new Set{ + OASOrdSide.BUY, + OASOrdSide.SELL + }; + Set actual = new Set(OASOrdSide.values()); + System.assertEquals(expected, actual); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdSideTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls new file mode 100644 index 0000000000..72fd3d6523 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls @@ -0,0 +1,27 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Order statuses and the lifecycle are documented in the separate section: EMS / Starter Guide / Order Lifecycle\n + */ +public enum OASOrdStatus { + RECEIVED, + ROUTING, + ROUTED, + NEW, + PENDING_CANCEL, + PARTIALLY_FILLED, + FILLED, + CANCELED, + REJECTED +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatus.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls new file mode 100644 index 0000000000..eb15805863 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls @@ -0,0 +1,19 @@ +@isTest +private class OASOrdStatusTest { + @isTest + private static void allowableValues() { + Set expected = new Set{ + OASOrdStatus.RECEIVED, + OASOrdStatus.ROUTING, + OASOrdStatus.ROUTED, + OASOrdStatus.NEW, + OASOrdStatus.PENDING_CANCEL, + OASOrdStatus.PARTIALLY_FILLED, + OASOrdStatus.FILLED, + OASOrdStatus.CANCELED, + OASOrdStatus.REJECTED + }; + Set actual = new Set(OASOrdStatus.values()); + System.assertEquals(expected, actual); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdStatusTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls new file mode 100644 index 0000000000..088fd940ef --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls @@ -0,0 +1,19 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Order types are documented in the separate section: EMS / Starter Guide / Order parameters / Order type\n + */ +public enum OASOrdType { + LIMIT +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdType.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls new file mode 100644 index 0000000000..e0546b2ca3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls @@ -0,0 +1,11 @@ +@isTest +private class OASOrdTypeTest { + @isTest + private static void allowableValues() { + Set expected = new Set{ + OASOrdType.LIMIT + }; + Set actual = new Set(OASOrdType.values()); + System.assertEquals(expected, actual); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdTypeTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls new file mode 100644 index 0000000000..2b98efb878 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls @@ -0,0 +1,51 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Cancel all orders request object. + */ +public class OASOrderCancelAllRequest implements OAS.MappedProperties { + /** + * Identifier of the exchange from which active orders should be canceled. + * @return exchangeId + */ + public String exchangeId { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASOrderCancelAllRequest getExample() { + OASOrderCancelAllRequest orderCancelAllRequest = new OASOrderCancelAllRequest(); + orderCancelAllRequest.exchangeId = 'KRAKEN'; + return orderCancelAllRequest; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASOrderCancelAllRequest) { + OASOrderCancelAllRequest orderCancelAllRequest = (OASOrderCancelAllRequest) obj; + return this.exchangeId == orderCancelAllRequest.exchangeId; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls new file mode 100644 index 0000000000..c9eaaa7cee --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls @@ -0,0 +1,78 @@ +@isTest +private class OASOrderCancelAllRequestTest { + @isTest + private static void equalsSameInstance() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = orderCancelAllRequest1; + OASOrderCancelAllRequest orderCancelAllRequest3 = new OASOrderCancelAllRequest(); + OASOrderCancelAllRequest orderCancelAllRequest4 = orderCancelAllRequest3; + + System.assert(orderCancelAllRequest1.equals(orderCancelAllRequest2)); + System.assert(orderCancelAllRequest2.equals(orderCancelAllRequest1)); + System.assert(orderCancelAllRequest1.equals(orderCancelAllRequest1)); + System.assert(orderCancelAllRequest3.equals(orderCancelAllRequest4)); + System.assert(orderCancelAllRequest4.equals(orderCancelAllRequest3)); + System.assert(orderCancelAllRequest3.equals(orderCancelAllRequest3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest3 = new OASOrderCancelAllRequest(); + OASOrderCancelAllRequest orderCancelAllRequest4 = new OASOrderCancelAllRequest(); + + System.assert(orderCancelAllRequest1.equals(orderCancelAllRequest2)); + System.assert(orderCancelAllRequest2.equals(orderCancelAllRequest1)); + System.assert(orderCancelAllRequest3.equals(orderCancelAllRequest4)); + System.assert(orderCancelAllRequest4.equals(orderCancelAllRequest3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = new OASOrderCancelAllRequest(); + + System.assertEquals(false, orderCancelAllRequest1.equals('foo')); + System.assertEquals(false, orderCancelAllRequest2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = new OASOrderCancelAllRequest(); + OASOrderCancelAllRequest orderCancelAllRequest3; + + System.assertEquals(false, orderCancelAllRequest1.equals(orderCancelAllRequest3)); + System.assertEquals(false, orderCancelAllRequest2.equals(orderCancelAllRequest3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = new OASOrderCancelAllRequest(); + + System.assertEquals(orderCancelAllRequest1.hashCode(), orderCancelAllRequest1.hashCode()); + System.assertEquals(orderCancelAllRequest2.hashCode(), orderCancelAllRequest2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASOrderCancelAllRequest orderCancelAllRequest1 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest2 = OASOrderCancelAllRequest.getExample(); + OASOrderCancelAllRequest orderCancelAllRequest3 = new OASOrderCancelAllRequest(); + OASOrderCancelAllRequest orderCancelAllRequest4 = new OASOrderCancelAllRequest(); + + System.assert(orderCancelAllRequest1.equals(orderCancelAllRequest2)); + System.assert(orderCancelAllRequest3.equals(orderCancelAllRequest4)); + System.assertEquals(orderCancelAllRequest1.hashCode(), orderCancelAllRequest2.hashCode()); + System.assertEquals(orderCancelAllRequest3.hashCode(), orderCancelAllRequest4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASOrderCancelAllRequest orderCancelAllRequest = new OASOrderCancelAllRequest(); + Map x-property-mappings = orderCancelAllRequest.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelAllRequestTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls new file mode 100644 index 0000000000..fd30f2c080 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls @@ -0,0 +1,91 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Cancel single order request object. + */ +public class OASOrderCancelSingleRequest implements OAS.MappedProperties { + /** + * Exchange identifier used to identify the routing destination. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + * @return exchangeOrderId + */ + public String exchangeOrderId { get; set; } + + /** + * The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + * @return clientOrderId + */ + public String clientOrderId { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'exchange_order_id' => 'exchangeOrderId', + 'client_order_id' => 'clientOrderId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'exchange_order_id' => 'exchangeOrderId', + 'client_order_id' => 'clientOrderId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'exchange_order_id' => 'exchangeOrderId', + 'client_order_id' => 'clientOrderId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASOrderCancelSingleRequest getExample() { + OASOrderCancelSingleRequest orderCancelSingleRequest = new OASOrderCancelSingleRequest(); + orderCancelSingleRequest.exchangeId = 'KRAKEN'; + orderCancelSingleRequest.exchangeOrderId = '3456456754'; + orderCancelSingleRequest.clientOrderId = '6ab36bc1-344d-432e-ac6d-0bf44ee64c2b'; + return orderCancelSingleRequest; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASOrderCancelSingleRequest) { + OASOrderCancelSingleRequest orderCancelSingleRequest = (OASOrderCancelSingleRequest) obj; + return this.exchangeId == orderCancelSingleRequest.exchangeId + && this.exchangeOrderId == orderCancelSingleRequest.exchangeOrderId + && this.clientOrderId == orderCancelSingleRequest.clientOrderId; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (exchangeOrderId == null ? 0 : System.hashCode(exchangeOrderId)); + hashCode = (17 * hashCode) + (clientOrderId == null ? 0 : System.hashCode(clientOrderId)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls new file mode 100644 index 0000000000..a785e45739 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls @@ -0,0 +1,80 @@ +@isTest +private class OASOrderCancelSingleRequestTest { + @isTest + private static void equalsSameInstance() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = orderCancelSingleRequest1; + OASOrderCancelSingleRequest orderCancelSingleRequest3 = new OASOrderCancelSingleRequest(); + OASOrderCancelSingleRequest orderCancelSingleRequest4 = orderCancelSingleRequest3; + + System.assert(orderCancelSingleRequest1.equals(orderCancelSingleRequest2)); + System.assert(orderCancelSingleRequest2.equals(orderCancelSingleRequest1)); + System.assert(orderCancelSingleRequest1.equals(orderCancelSingleRequest1)); + System.assert(orderCancelSingleRequest3.equals(orderCancelSingleRequest4)); + System.assert(orderCancelSingleRequest4.equals(orderCancelSingleRequest3)); + System.assert(orderCancelSingleRequest3.equals(orderCancelSingleRequest3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest3 = new OASOrderCancelSingleRequest(); + OASOrderCancelSingleRequest orderCancelSingleRequest4 = new OASOrderCancelSingleRequest(); + + System.assert(orderCancelSingleRequest1.equals(orderCancelSingleRequest2)); + System.assert(orderCancelSingleRequest2.equals(orderCancelSingleRequest1)); + System.assert(orderCancelSingleRequest3.equals(orderCancelSingleRequest4)); + System.assert(orderCancelSingleRequest4.equals(orderCancelSingleRequest3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = new OASOrderCancelSingleRequest(); + + System.assertEquals(false, orderCancelSingleRequest1.equals('foo')); + System.assertEquals(false, orderCancelSingleRequest2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = new OASOrderCancelSingleRequest(); + OASOrderCancelSingleRequest orderCancelSingleRequest3; + + System.assertEquals(false, orderCancelSingleRequest1.equals(orderCancelSingleRequest3)); + System.assertEquals(false, orderCancelSingleRequest2.equals(orderCancelSingleRequest3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = new OASOrderCancelSingleRequest(); + + System.assertEquals(orderCancelSingleRequest1.hashCode(), orderCancelSingleRequest1.hashCode()); + System.assertEquals(orderCancelSingleRequest2.hashCode(), orderCancelSingleRequest2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASOrderCancelSingleRequest orderCancelSingleRequest1 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest2 = OASOrderCancelSingleRequest.getExample(); + OASOrderCancelSingleRequest orderCancelSingleRequest3 = new OASOrderCancelSingleRequest(); + OASOrderCancelSingleRequest orderCancelSingleRequest4 = new OASOrderCancelSingleRequest(); + + System.assert(orderCancelSingleRequest1.equals(orderCancelSingleRequest2)); + System.assert(orderCancelSingleRequest3.equals(orderCancelSingleRequest4)); + System.assertEquals(orderCancelSingleRequest1.hashCode(), orderCancelSingleRequest2.hashCode()); + System.assertEquals(orderCancelSingleRequest3.hashCode(), orderCancelSingleRequest4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASOrderCancelSingleRequest orderCancelSingleRequest = new OASOrderCancelSingleRequest(); + Map x-property-mappings = orderCancelSingleRequest.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + System.assertEquals('exchangeOrderId', x-property-mappings.get('exchange_order_id')); + System.assertEquals('clientOrderId', x-property-mappings.get('client_order_id')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderCancelSingleRequestTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls new file mode 100644 index 0000000000..a7bd62fe3a --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls @@ -0,0 +1,597 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * The order execution report object. + */ +public class OASOrderExecutionReport implements OASOrderNewSingleRequest, OASOrderExecutionReportAllOf, OAS.MappedProperties { + /** + * Exchange identifier used to identify the routing destination. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * The unique identifier of the order assigned by the client. + * @return clientOrderId + */ + public String clientOrderId { get; set; } + + /** + * Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + * @return symbolIdExchange + */ + public String symbolIdExchange { get; set; } + + /** + * CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + * @return symbolIdCoinapi + */ + public String symbolIdCoinapi { get; set; } + + /** + * Order quantity. + * @return amountOrder + */ + public Double amountOrder { get; set; } + + /** + * Order price. + * @return price + */ + public Double price { get; set; } + + /** + * Get side + * @return side + */ + public OASOrdSide side { get; set; } + + /** + * Get orderType + * @return orderType + */ + public OASOrdType orderType { get; set; } + + /** + * Get timeInForce + * @return timeInForce + */ + public OASTimeInForce timeInForce { get; set; } + + /** + * Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + * @return expireTime + */ + public Date expireTime { get; set; } + + /** + * Gets or Sets execInst + */ + public enum ExecInstEnum { + MAKER_OR_CANCEL, + AUCTION_ONLY, + INDICATION_OF_INTEREST + } + + /** + * Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions\n + * @return execInst + */ + public List execInst { get; set; } + + /** + * The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + * @return clientOrderIdFormatExchange + */ + public String clientOrderIdFormatExchange { get; set; } + + /** + * Unique identifier of the order assigned by the exchange or executing system. + * @return exchangeOrderId + */ + public String exchangeOrderId { get; set; } + + /** + * Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + * @return amountOpen + */ + public Double amountOpen { get; set; } + + /** + * Total quantity filled. + * @return amountFilled + */ + public Double amountFilled { get; set; } + + /** + * Calculated average price of all fills on this order. + * @return avgPx + */ + public Double avgPx { get; set; } + + /** + * Get status + * @return status + */ + public OASOrdStatus status { get; set; } + + /** + * Timestamped history of order status changes. + * @return statusHistory + */ + public List> statusHistory { get; set; } + + /** + * Error message. + * @return errorMessage + */ + public String errorMessage { get; set; } + + /** + * Relay fill information on working orders. + * @return fills + */ + public List fills { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst', + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public OASOrderExecutionReport() { + execInst = new List(); + statusHistory = new List>(); + fills = new List(); + } + + public static OASOrderExecutionReport getExample() { + OASOrderExecutionReport orderExecutionReport = new OASOrderExecutionReport(); + orderExecutionReport.exchangeId = 'KRAKEN'; + orderExecutionReport.clientOrderId = '6ab36bc1-344d-432e-ac6d-0bf44ee64c2b'; + orderExecutionReport.symbolIdExchange = 'XBT/USDT'; + orderExecutionReport.symbolIdCoinapi = 'KRAKEN_SPOT_BTC_USDT'; + orderExecutionReport.amountOrder = 0.045; + orderExecutionReport.price = 0.0783; + orderExecutionReport.side = OASOrdSide.getExample(); + orderExecutionReport.orderType = OASOrdType.getExample(); + orderExecutionReport.timeInForce = OASTimeInForce.getExample(); + orderExecutionReport.expireTime = Date.getExample(); + orderExecutionReport.execInst = List.LIST_EXECINSTENUM_NEW_LIST_STRING_MAKER_OR_CANCEL_; + orderExecutionReport.clientOrderIdFormatExchange = 'f81211e2-27c4-b86a-8143-01088ba9222c'; + orderExecutionReport.exchangeOrderId = '3456456754'; + orderExecutionReport.amountOpen = 0.22; + orderExecutionReport.amountFilled = 0.0; + orderExecutionReport.avgPx = 0.0783; + orderExecutionReport.status = OASOrdStatus.getExample(); + orderExecutionReport.statusHistory = new List>{new List{'[["RECEIVED","2020-05-27T11:16:20.1677709Z"],["REJECTED","2020-05-27T11:16:20.1677710Z"]]'}}; + orderExecutionReport.errorMessage = '{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol \'BTCUSD\' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}'; + orderExecutionReport.fills = new List{OASFills.getExample()}; + return orderExecutionReport; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASOrderExecutionReport) { + OASOrderExecutionReport orderExecutionReport = (OASOrderExecutionReport) obj; + return this.exchangeId == orderExecutionReport.exchangeId + && this.clientOrderId == orderExecutionReport.clientOrderId + && this.symbolIdExchange == orderExecutionReport.symbolIdExchange + && this.symbolIdCoinapi == orderExecutionReport.symbolIdCoinapi + && this.amountOrder == orderExecutionReport.amountOrder + && this.price == orderExecutionReport.price + && this.side == orderExecutionReport.side + && this.orderType == orderExecutionReport.orderType + && this.timeInForce == orderExecutionReport.timeInForce + && this.expireTime == orderExecutionReport.expireTime + && this.execInst == orderExecutionReport.execInst + && this.clientOrderIdFormatExchange == orderExecutionReport.clientOrderIdFormatExchange + && this.exchangeOrderId == orderExecutionReport.exchangeOrderId + && this.amountOpen == orderExecutionReport.amountOpen + && this.amountFilled == orderExecutionReport.amountFilled + && this.avgPx == orderExecutionReport.avgPx + && this.status == orderExecutionReport.status + && this.statusHistory == orderExecutionReport.statusHistory + && this.errorMessage == orderExecutionReport.errorMessage + && this.fills == orderExecutionReport.fills; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (clientOrderId == null ? 0 : System.hashCode(clientOrderId)); + hashCode = (17 * hashCode) + (symbolIdExchange == null ? 0 : System.hashCode(symbolIdExchange)); + hashCode = (17 * hashCode) + (symbolIdCoinapi == null ? 0 : System.hashCode(symbolIdCoinapi)); + hashCode = (17 * hashCode) + (amountOrder == null ? 0 : System.hashCode(amountOrder)); + hashCode = (17 * hashCode) + (price == null ? 0 : System.hashCode(price)); + hashCode = (17 * hashCode) + (side == null ? 0 : System.hashCode(side)); + hashCode = (17 * hashCode) + (orderType == null ? 0 : System.hashCode(orderType)); + hashCode = (17 * hashCode) + (timeInForce == null ? 0 : System.hashCode(timeInForce)); + hashCode = (17 * hashCode) + (expireTime == null ? 0 : System.hashCode(expireTime)); + hashCode = (17 * hashCode) + (execInst == null ? 0 : System.hashCode(execInst)); + hashCode = (17 * hashCode) + (clientOrderIdFormatExchange == null ? 0 : System.hashCode(clientOrderIdFormatExchange)); + hashCode = (17 * hashCode) + (exchangeOrderId == null ? 0 : System.hashCode(exchangeOrderId)); + hashCode = (17 * hashCode) + (amountOpen == null ? 0 : System.hashCode(amountOpen)); + hashCode = (17 * hashCode) + (amountFilled == null ? 0 : System.hashCode(amountFilled)); + hashCode = (17 * hashCode) + (avgPx == null ? 0 : System.hashCode(avgPx)); + hashCode = (17 * hashCode) + (status == null ? 0 : System.hashCode(status)); + hashCode = (17 * hashCode) + (statusHistory == null ? 0 : System.hashCode(statusHistory)); + hashCode = (17 * hashCode) + (errorMessage == null ? 0 : System.hashCode(errorMessage)); + hashCode = (17 * hashCode) + (fills == null ? 0 : System.hashCode(fills)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReport.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls new file mode 100644 index 0000000000..95c7a45c29 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls @@ -0,0 +1,218 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * The order execution report message. + */ +public class OASOrderExecutionReportAllOf implements OAS.MappedProperties { + /** + * The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + * @return clientOrderIdFormatExchange + */ + public String clientOrderIdFormatExchange { get; set; } + + /** + * Unique identifier of the order assigned by the exchange or executing system. + * @return exchangeOrderId + */ + public String exchangeOrderId { get; set; } + + /** + * Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + * @return amountOpen + */ + public Double amountOpen { get; set; } + + /** + * Total quantity filled. + * @return amountFilled + */ + public Double amountFilled { get; set; } + + /** + * Calculated average price of all fills on this order. + * @return avgPx + */ + public Double avgPx { get; set; } + + /** + * Get status + * @return status + */ + public OASOrdStatus status { get; set; } + + /** + * Timestamped history of order status changes. + * @return statusHistory + */ + public List> statusHistory { get; set; } + + /** + * Error message. + * @return errorMessage + */ + public String errorMessage { get; set; } + + /** + * Relay fill information on working orders. + * @return fills + */ + public List fills { get; set; } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'client_order_id_format_exchange' => 'clientOrderIdFormatExchange', + 'exchange_order_id' => 'exchangeOrderId', + 'amount_open' => 'amountOpen', + 'amount_filled' => 'amountFilled', + 'avg_px' => 'avgPx', + 'status_history' => 'statusHistory', + 'error_message' => 'errorMessage' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public OASOrderExecutionReportAllOf() { + statusHistory = new List>(); + fills = new List(); + } + + public static OASOrderExecutionReportAllOf getExample() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf = new OASOrderExecutionReportAllOf(); + orderExecutionReportAllOf.clientOrderIdFormatExchange = 'f81211e2-27c4-b86a-8143-01088ba9222c'; + orderExecutionReportAllOf.exchangeOrderId = '3456456754'; + orderExecutionReportAllOf.amountOpen = 0.22; + orderExecutionReportAllOf.amountFilled = 0.0; + orderExecutionReportAllOf.avgPx = 0.0783; + orderExecutionReportAllOf.status = OASOrdStatus.getExample(); + orderExecutionReportAllOf.statusHistory = new List>{new List{'[["RECEIVED","2020-05-27T11:16:20.1677709Z"],["REJECTED","2020-05-27T11:16:20.1677710Z"]]'}}; + orderExecutionReportAllOf.errorMessage = '{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol \'BTCUSD\' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}'; + orderExecutionReportAllOf.fills = new List{OASFills.getExample()}; + return orderExecutionReportAllOf; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASOrderExecutionReportAllOf) { + OASOrderExecutionReportAllOf orderExecutionReportAllOf = (OASOrderExecutionReportAllOf) obj; + return this.clientOrderIdFormatExchange == orderExecutionReportAllOf.clientOrderIdFormatExchange + && this.exchangeOrderId == orderExecutionReportAllOf.exchangeOrderId + && this.amountOpen == orderExecutionReportAllOf.amountOpen + && this.amountFilled == orderExecutionReportAllOf.amountFilled + && this.avgPx == orderExecutionReportAllOf.avgPx + && this.status == orderExecutionReportAllOf.status + && this.statusHistory == orderExecutionReportAllOf.statusHistory + && this.errorMessage == orderExecutionReportAllOf.errorMessage + && this.fills == orderExecutionReportAllOf.fills; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (clientOrderIdFormatExchange == null ? 0 : System.hashCode(clientOrderIdFormatExchange)); + hashCode = (17 * hashCode) + (exchangeOrderId == null ? 0 : System.hashCode(exchangeOrderId)); + hashCode = (17 * hashCode) + (amountOpen == null ? 0 : System.hashCode(amountOpen)); + hashCode = (17 * hashCode) + (amountFilled == null ? 0 : System.hashCode(amountFilled)); + hashCode = (17 * hashCode) + (avgPx == null ? 0 : System.hashCode(avgPx)); + hashCode = (17 * hashCode) + (status == null ? 0 : System.hashCode(status)); + hashCode = (17 * hashCode) + (statusHistory == null ? 0 : System.hashCode(statusHistory)); + hashCode = (17 * hashCode) + (errorMessage == null ? 0 : System.hashCode(errorMessage)); + hashCode = (17 * hashCode) + (fills == null ? 0 : System.hashCode(fills)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOf.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls new file mode 100644 index 0000000000..03545eb6df --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls @@ -0,0 +1,98 @@ +@isTest +private class OASOrderExecutionReportAllOfTest { + @isTest + private static void equalsSameInstance() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = orderExecutionReportAllOf1; + OASOrderExecutionReportAllOf orderExecutionReportAllOf3 = new OASOrderExecutionReportAllOf(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf4 = orderExecutionReportAllOf3; + + System.assert(orderExecutionReportAllOf1.equals(orderExecutionReportAllOf2)); + System.assert(orderExecutionReportAllOf2.equals(orderExecutionReportAllOf1)); + System.assert(orderExecutionReportAllOf1.equals(orderExecutionReportAllOf1)); + System.assert(orderExecutionReportAllOf3.equals(orderExecutionReportAllOf4)); + System.assert(orderExecutionReportAllOf4.equals(orderExecutionReportAllOf3)); + System.assert(orderExecutionReportAllOf3.equals(orderExecutionReportAllOf3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf3 = new OASOrderExecutionReportAllOf(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf4 = new OASOrderExecutionReportAllOf(); + + System.assert(orderExecutionReportAllOf1.equals(orderExecutionReportAllOf2)); + System.assert(orderExecutionReportAllOf2.equals(orderExecutionReportAllOf1)); + System.assert(orderExecutionReportAllOf3.equals(orderExecutionReportAllOf4)); + System.assert(orderExecutionReportAllOf4.equals(orderExecutionReportAllOf3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = new OASOrderExecutionReportAllOf(); + + System.assertEquals(false, orderExecutionReportAllOf1.equals('foo')); + System.assertEquals(false, orderExecutionReportAllOf2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = new OASOrderExecutionReportAllOf(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf3; + + System.assertEquals(false, orderExecutionReportAllOf1.equals(orderExecutionReportAllOf3)); + System.assertEquals(false, orderExecutionReportAllOf2.equals(orderExecutionReportAllOf3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = new OASOrderExecutionReportAllOf(); + + System.assertEquals(orderExecutionReportAllOf1.hashCode(), orderExecutionReportAllOf1.hashCode()); + System.assertEquals(orderExecutionReportAllOf2.hashCode(), orderExecutionReportAllOf2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf1 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf2 = OASOrderExecutionReportAllOf.getExample(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf3 = new OASOrderExecutionReportAllOf(); + OASOrderExecutionReportAllOf orderExecutionReportAllOf4 = new OASOrderExecutionReportAllOf(); + + System.assert(orderExecutionReportAllOf1.equals(orderExecutionReportAllOf2)); + System.assert(orderExecutionReportAllOf3.equals(orderExecutionReportAllOf4)); + System.assertEquals(orderExecutionReportAllOf1.hashCode(), orderExecutionReportAllOf2.hashCode()); + System.assertEquals(orderExecutionReportAllOf3.hashCode(), orderExecutionReportAllOf4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf = new OASOrderExecutionReportAllOf(); + Map x-property-mappings = orderExecutionReportAllOf.getx-property-mappings(); + System.assertEquals('clientOrderIdFormatExchange', x-property-mappings.get('client_order_id_format_exchange')); + System.assertEquals('exchangeOrderId', x-property-mappings.get('exchange_order_id')); + System.assertEquals('amountOpen', x-property-mappings.get('amount_open')); + System.assertEquals('amountFilled', x-property-mappings.get('amount_filled')); + System.assertEquals('avgPx', x-property-mappings.get('avg_px')); + System.assertEquals('statusHistory', x-property-mappings.get('status_history')); + System.assertEquals('errorMessage', x-property-mappings.get('error_message')); + } + + @isTest + private static void defaultValuesPopulated() { + OASOrderExecutionReportAllOf orderExecutionReportAllOf = new OASOrderExecutionReportAllOf(); + System.assertEquals(new List>(), orderExecutionReportAllOf.statusHistory); + System.assertEquals(new List(), orderExecutionReportAllOf.fills); + System.assertEquals(null, orderExecutionReportAllOf.clientOrderIdFormatExchange); + System.assertEquals(null, orderExecutionReportAllOf.exchangeOrderId); + System.assertEquals(null, orderExecutionReportAllOf.amountOpen); + System.assertEquals(null, orderExecutionReportAllOf.amountFilled); + System.assertEquals(null, orderExecutionReportAllOf.avgPx); + System.assertEquals(null, orderExecutionReportAllOf.status); + System.assertEquals(null, orderExecutionReportAllOf.errorMessage); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportAllOfTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls new file mode 100644 index 0000000000..a8da699f56 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls @@ -0,0 +1,118 @@ +@isTest +private class OASOrderExecutionReportTest { + @isTest + private static void equalsSameInstance() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = orderExecutionReport1; + OASOrderExecutionReport orderExecutionReport3 = new OASOrderExecutionReport(); + OASOrderExecutionReport orderExecutionReport4 = orderExecutionReport3; + + System.assert(orderExecutionReport1.equals(orderExecutionReport2)); + System.assert(orderExecutionReport2.equals(orderExecutionReport1)); + System.assert(orderExecutionReport1.equals(orderExecutionReport1)); + System.assert(orderExecutionReport3.equals(orderExecutionReport4)); + System.assert(orderExecutionReport4.equals(orderExecutionReport3)); + System.assert(orderExecutionReport3.equals(orderExecutionReport3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport3 = new OASOrderExecutionReport(); + OASOrderExecutionReport orderExecutionReport4 = new OASOrderExecutionReport(); + + System.assert(orderExecutionReport1.equals(orderExecutionReport2)); + System.assert(orderExecutionReport2.equals(orderExecutionReport1)); + System.assert(orderExecutionReport3.equals(orderExecutionReport4)); + System.assert(orderExecutionReport4.equals(orderExecutionReport3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = new OASOrderExecutionReport(); + + System.assertEquals(false, orderExecutionReport1.equals('foo')); + System.assertEquals(false, orderExecutionReport2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = new OASOrderExecutionReport(); + OASOrderExecutionReport orderExecutionReport3; + + System.assertEquals(false, orderExecutionReport1.equals(orderExecutionReport3)); + System.assertEquals(false, orderExecutionReport2.equals(orderExecutionReport3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = new OASOrderExecutionReport(); + + System.assertEquals(orderExecutionReport1.hashCode(), orderExecutionReport1.hashCode()); + System.assertEquals(orderExecutionReport2.hashCode(), orderExecutionReport2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASOrderExecutionReport orderExecutionReport1 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport2 = OASOrderExecutionReport.getExample(); + OASOrderExecutionReport orderExecutionReport3 = new OASOrderExecutionReport(); + OASOrderExecutionReport orderExecutionReport4 = new OASOrderExecutionReport(); + + System.assert(orderExecutionReport1.equals(orderExecutionReport2)); + System.assert(orderExecutionReport3.equals(orderExecutionReport4)); + System.assertEquals(orderExecutionReport1.hashCode(), orderExecutionReport2.hashCode()); + System.assertEquals(orderExecutionReport3.hashCode(), orderExecutionReport4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASOrderExecutionReport orderExecutionReport = new OASOrderExecutionReport(); + Map x-property-mappings = orderExecutionReport.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + System.assertEquals('clientOrderId', x-property-mappings.get('client_order_id')); + System.assertEquals('symbolIdExchange', x-property-mappings.get('symbol_id_exchange')); + System.assertEquals('symbolIdCoinapi', x-property-mappings.get('symbol_id_coinapi')); + System.assertEquals('amountOrder', x-property-mappings.get('amount_order')); + System.assertEquals('orderType', x-property-mappings.get('order_type')); + System.assertEquals('timeInForce', x-property-mappings.get('time_in_force')); + System.assertEquals('expireTime', x-property-mappings.get('expire_time')); + System.assertEquals('execInst', x-property-mappings.get('exec_inst')); + System.assertEquals('clientOrderIdFormatExchange', x-property-mappings.get('client_order_id_format_exchange')); + System.assertEquals('exchangeOrderId', x-property-mappings.get('exchange_order_id')); + System.assertEquals('amountOpen', x-property-mappings.get('amount_open')); + System.assertEquals('amountFilled', x-property-mappings.get('amount_filled')); + System.assertEquals('avgPx', x-property-mappings.get('avg_px')); + System.assertEquals('statusHistory', x-property-mappings.get('status_history')); + System.assertEquals('errorMessage', x-property-mappings.get('error_message')); + } + + @isTest + private static void defaultValuesPopulated() { + OASOrderExecutionReport orderExecutionReport = new OASOrderExecutionReport(); + System.assertEquals(new List(), orderExecutionReport.execInst); + System.assertEquals(new List>(), orderExecutionReport.statusHistory); + System.assertEquals(new List(), orderExecutionReport.fills); + System.assertEquals(null, orderExecutionReport.exchangeId); + System.assertEquals(null, orderExecutionReport.clientOrderId); + System.assertEquals(null, orderExecutionReport.symbolIdExchange); + System.assertEquals(null, orderExecutionReport.symbolIdCoinapi); + System.assertEquals(null, orderExecutionReport.amountOrder); + System.assertEquals(null, orderExecutionReport.price); + System.assertEquals(null, orderExecutionReport.side); + System.assertEquals(null, orderExecutionReport.orderType); + System.assertEquals(null, orderExecutionReport.timeInForce); + System.assertEquals(null, orderExecutionReport.expireTime); + System.assertEquals(null, orderExecutionReport.clientOrderIdFormatExchange); + System.assertEquals(null, orderExecutionReport.exchangeOrderId); + System.assertEquals(null, orderExecutionReport.amountOpen); + System.assertEquals(null, orderExecutionReport.amountFilled); + System.assertEquals(null, orderExecutionReport.avgPx); + System.assertEquals(null, orderExecutionReport.status); + System.assertEquals(null, orderExecutionReport.errorMessage); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderExecutionReportTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls new file mode 100644 index 0000000000..b4e02c9233 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls @@ -0,0 +1,290 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * The new order message. + */ +public class OASOrderNewSingleRequest implements OAS.MappedProperties { + /** + * Exchange identifier used to identify the routing destination. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * The unique identifier of the order assigned by the client. + * @return clientOrderId + */ + public String clientOrderId { get; set; } + + /** + * Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + * @return symbolIdExchange + */ + public String symbolIdExchange { get; set; } + + /** + * CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + * @return symbolIdCoinapi + */ + public String symbolIdCoinapi { get; set; } + + /** + * Order quantity. + * @return amountOrder + */ + public Double amountOrder { get; set; } + + /** + * Order price. + * @return price + */ + public Double price { get; set; } + + /** + * Get side + * @return side + */ + public OASOrdSide side { get; set; } + + /** + * Get orderType + * @return orderType + */ + public OASOrdType orderType { get; set; } + + /** + * Get timeInForce + * @return timeInForce + */ + public OASTimeInForce timeInForce { get; set; } + + /** + * Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + * @return expireTime + */ + public Date expireTime { get; set; } + + /** + * Gets or Sets execInst + */ + public enum ExecInstEnum { + MAKER_OR_CANCEL, + AUCTION_ONLY, + INDICATION_OF_INTEREST + } + + /** + * Order execution instructions are documented in the separate section: EMS / Starter Guide / Order parameters / Execution instructions\n + * @return execInst + */ + public List execInst { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId', + 'client_order_id' => 'clientOrderId', + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'amount_order' => 'amountOrder', + 'order_type' => 'orderType', + 'time_in_force' => 'timeInForce', + 'expire_time' => 'expireTime', + 'exec_inst' => 'execInst' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public OASOrderNewSingleRequest() { + execInst = new List(); + } + + public static OASOrderNewSingleRequest getExample() { + OASOrderNewSingleRequest orderNewSingleRequest = new OASOrderNewSingleRequest(); + orderNewSingleRequest.exchangeId = 'KRAKEN'; + orderNewSingleRequest.clientOrderId = '6ab36bc1-344d-432e-ac6d-0bf44ee64c2b'; + orderNewSingleRequest.symbolIdExchange = 'XBT/USDT'; + orderNewSingleRequest.symbolIdCoinapi = 'KRAKEN_SPOT_BTC_USDT'; + orderNewSingleRequest.amountOrder = 0.045; + orderNewSingleRequest.price = 0.0783; + orderNewSingleRequest.side = OASOrdSide.getExample(); + orderNewSingleRequest.orderType = OASOrdType.getExample(); + orderNewSingleRequest.timeInForce = OASTimeInForce.getExample(); + orderNewSingleRequest.expireTime = Date.getExample(); + orderNewSingleRequest.execInst = List.LIST_EXECINSTENUM_NEW_LIST_STRING_MAKER_OR_CANCEL_; + return orderNewSingleRequest; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASOrderNewSingleRequest) { + OASOrderNewSingleRequest orderNewSingleRequest = (OASOrderNewSingleRequest) obj; + return this.exchangeId == orderNewSingleRequest.exchangeId + && this.clientOrderId == orderNewSingleRequest.clientOrderId + && this.symbolIdExchange == orderNewSingleRequest.symbolIdExchange + && this.symbolIdCoinapi == orderNewSingleRequest.symbolIdCoinapi + && this.amountOrder == orderNewSingleRequest.amountOrder + && this.price == orderNewSingleRequest.price + && this.side == orderNewSingleRequest.side + && this.orderType == orderNewSingleRequest.orderType + && this.timeInForce == orderNewSingleRequest.timeInForce + && this.expireTime == orderNewSingleRequest.expireTime + && this.execInst == orderNewSingleRequest.execInst; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (clientOrderId == null ? 0 : System.hashCode(clientOrderId)); + hashCode = (17 * hashCode) + (symbolIdExchange == null ? 0 : System.hashCode(symbolIdExchange)); + hashCode = (17 * hashCode) + (symbolIdCoinapi == null ? 0 : System.hashCode(symbolIdCoinapi)); + hashCode = (17 * hashCode) + (amountOrder == null ? 0 : System.hashCode(amountOrder)); + hashCode = (17 * hashCode) + (price == null ? 0 : System.hashCode(price)); + hashCode = (17 * hashCode) + (side == null ? 0 : System.hashCode(side)); + hashCode = (17 * hashCode) + (orderType == null ? 0 : System.hashCode(orderType)); + hashCode = (17 * hashCode) + (timeInForce == null ? 0 : System.hashCode(timeInForce)); + hashCode = (17 * hashCode) + (expireTime == null ? 0 : System.hashCode(expireTime)); + hashCode = (17 * hashCode) + (execInst == null ? 0 : System.hashCode(execInst)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls new file mode 100644 index 0000000000..38de74ef96 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls @@ -0,0 +1,102 @@ +@isTest +private class OASOrderNewSingleRequestTest { + @isTest + private static void equalsSameInstance() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = orderNewSingleRequest1; + OASOrderNewSingleRequest orderNewSingleRequest3 = new OASOrderNewSingleRequest(); + OASOrderNewSingleRequest orderNewSingleRequest4 = orderNewSingleRequest3; + + System.assert(orderNewSingleRequest1.equals(orderNewSingleRequest2)); + System.assert(orderNewSingleRequest2.equals(orderNewSingleRequest1)); + System.assert(orderNewSingleRequest1.equals(orderNewSingleRequest1)); + System.assert(orderNewSingleRequest3.equals(orderNewSingleRequest4)); + System.assert(orderNewSingleRequest4.equals(orderNewSingleRequest3)); + System.assert(orderNewSingleRequest3.equals(orderNewSingleRequest3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest3 = new OASOrderNewSingleRequest(); + OASOrderNewSingleRequest orderNewSingleRequest4 = new OASOrderNewSingleRequest(); + + System.assert(orderNewSingleRequest1.equals(orderNewSingleRequest2)); + System.assert(orderNewSingleRequest2.equals(orderNewSingleRequest1)); + System.assert(orderNewSingleRequest3.equals(orderNewSingleRequest4)); + System.assert(orderNewSingleRequest4.equals(orderNewSingleRequest3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = new OASOrderNewSingleRequest(); + + System.assertEquals(false, orderNewSingleRequest1.equals('foo')); + System.assertEquals(false, orderNewSingleRequest2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = new OASOrderNewSingleRequest(); + OASOrderNewSingleRequest orderNewSingleRequest3; + + System.assertEquals(false, orderNewSingleRequest1.equals(orderNewSingleRequest3)); + System.assertEquals(false, orderNewSingleRequest2.equals(orderNewSingleRequest3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = new OASOrderNewSingleRequest(); + + System.assertEquals(orderNewSingleRequest1.hashCode(), orderNewSingleRequest1.hashCode()); + System.assertEquals(orderNewSingleRequest2.hashCode(), orderNewSingleRequest2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASOrderNewSingleRequest orderNewSingleRequest1 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest2 = OASOrderNewSingleRequest.getExample(); + OASOrderNewSingleRequest orderNewSingleRequest3 = new OASOrderNewSingleRequest(); + OASOrderNewSingleRequest orderNewSingleRequest4 = new OASOrderNewSingleRequest(); + + System.assert(orderNewSingleRequest1.equals(orderNewSingleRequest2)); + System.assert(orderNewSingleRequest3.equals(orderNewSingleRequest4)); + System.assertEquals(orderNewSingleRequest1.hashCode(), orderNewSingleRequest2.hashCode()); + System.assertEquals(orderNewSingleRequest3.hashCode(), orderNewSingleRequest4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASOrderNewSingleRequest orderNewSingleRequest = new OASOrderNewSingleRequest(); + Map x-property-mappings = orderNewSingleRequest.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + System.assertEquals('clientOrderId', x-property-mappings.get('client_order_id')); + System.assertEquals('symbolIdExchange', x-property-mappings.get('symbol_id_exchange')); + System.assertEquals('symbolIdCoinapi', x-property-mappings.get('symbol_id_coinapi')); + System.assertEquals('amountOrder', x-property-mappings.get('amount_order')); + System.assertEquals('orderType', x-property-mappings.get('order_type')); + System.assertEquals('timeInForce', x-property-mappings.get('time_in_force')); + System.assertEquals('expireTime', x-property-mappings.get('expire_time')); + System.assertEquals('execInst', x-property-mappings.get('exec_inst')); + } + + @isTest + private static void defaultValuesPopulated() { + OASOrderNewSingleRequest orderNewSingleRequest = new OASOrderNewSingleRequest(); + System.assertEquals(new List(), orderNewSingleRequest.execInst); + System.assertEquals(null, orderNewSingleRequest.exchangeId); + System.assertEquals(null, orderNewSingleRequest.clientOrderId); + System.assertEquals(null, orderNewSingleRequest.symbolIdExchange); + System.assertEquals(null, orderNewSingleRequest.symbolIdCoinapi); + System.assertEquals(null, orderNewSingleRequest.amountOrder); + System.assertEquals(null, orderNewSingleRequest.price); + System.assertEquals(null, orderNewSingleRequest.side); + System.assertEquals(null, orderNewSingleRequest.orderType); + System.assertEquals(null, orderNewSingleRequest.timeInForce); + System.assertEquals(null, orderNewSingleRequest.expireTime); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrderNewSingleRequestTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls new file mode 100644 index 0000000000..fa512d0dcc --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls @@ -0,0 +1,151 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +public class OASOrdersApi { + OASClient client; + + public OASOrdersApi(OASClient client) { + this.client = client; + } + + public OASOrdersApi() { + this.client = new OASClient(); + } + + public OASClient getClient() { + return this.client; + } + + /** + * Cancel all orders request + * This request cancels all open orders on single specified exchange. + * @param oaSOrderCancelAllRequest OrderCancelAllRequest object. (required) + * @return OASMessageReject + * @throws OAS.ApiException if fails to make API call + */ + public OASMessageReject v1OrdersCancelAllPost(Map params) { + client.assertNotNull(params.get('oaSOrderCancelAllRequest'), 'oaSOrderCancelAllRequest'); + List query = new List(); + List form = new List(); + + return (OASMessageReject) client.invoke( + 'POST', '/v1/orders/cancel/all', + (OASOrderCancelAllRequest) params.get('oaSOrderCancelAllRequest'), + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List{ 'application/json' }, + new List(), + OASMessageReject.class + ); + } + /** + * Cancel order request + * Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + * @param oaSOrderCancelSingleRequest OrderCancelSingleRequest object. (required) + * @return OASOrderExecutionReport + * @throws OAS.ApiException if fails to make API call + */ + public OASOrderExecutionReport v1OrdersCancelPost(Map params) { + client.assertNotNull(params.get('oaSOrderCancelSingleRequest'), 'oaSOrderCancelSingleRequest'); + List query = new List(); + List form = new List(); + + return (OASOrderExecutionReport) client.invoke( + 'POST', '/v1/orders/cancel', + (OASOrderCancelSingleRequest) params.get('oaSOrderCancelSingleRequest'), + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List{ 'application/json' }, + new List(), + OASOrderExecutionReport.class + ); + } + /** + * Get open orders + * Get last execution reports for open orders across all or single exchange. + * @param exchangeId Filter the open orders to the specific exchange. (optional) + * @return List + * @throws OAS.ApiException if fails to make API call + */ + public List v1OrdersGet(Map params) { + List query = new List(); + + // cast query params to verify their expected type + query.addAll(client.makeParam('exchange_id', (String) params.get('exchangeId'))); + + List form = new List(); + + return (List) client.invoke( + 'GET', '/v1/orders', '', + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List(), + new List(), + List.class + ); + } + /** + * Send new order + * This request creating new order for the specific exchange. + * @param oaSOrderNewSingleRequest OrderNewSingleRequest object. (required) + * @return OASOrderExecutionReport + * @throws OAS.ApiException if fails to make API call + */ + public OASOrderExecutionReport v1OrdersPost(Map params) { + client.assertNotNull(params.get('oaSOrderNewSingleRequest'), 'oaSOrderNewSingleRequest'); + List query = new List(); + List form = new List(); + + return (OASOrderExecutionReport) client.invoke( + 'POST', '/v1/orders', + (OASOrderNewSingleRequest) params.get('oaSOrderNewSingleRequest'), + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List{ 'application/json' }, + new List(), + OASOrderExecutionReport.class + ); + } + /** + * Get order execution report + * Get the last order execution report for the specified order. The requested order does not need to be active or opened. + * @param clientOrderId The unique identifier of the order assigned by the client. (required) + * @return OASOrderExecutionReport + * @throws OAS.ApiException if fails to make API call + */ + public OASOrderExecutionReport v1OrdersStatusClientOrderIdGet(Map params) { + client.assertNotNull(params.get('clientOrderId'), 'clientOrderId'); + List query = new List(); + List form = new List(); + + return (OASOrderExecutionReport) client.invoke( + 'GET', '/v1/orders/status/{client_order_id}', '', + query, form, + new Map{ + 'client_order_id' => (String) params.get('clientOrderId') + }, + new Map(), + new List{ 'application/json' }, + new List(), + new List(), + OASOrderExecutionReport.class + ); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApi.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls new file mode 100644 index 0000000000..118175ddd3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls @@ -0,0 +1,162 @@ +@isTest +private class OASOrdersApiTest { + /** + * Cancel all orders request + * + * This request cancels all open orders on single specified exchange. + */ + @isTest + private static void v1OrdersCancelAllPostTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'oaSOrderCancelAllRequest' => '' + }; + + OASClient client; + OASOrdersApi api; + OASMessageReject response; + OASMessageReject expectedResponse; + String js = ''; + + api = new OASOrdersApi(new OASClient()); + + js = JSON.serialize(OASMessageReject.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = OASMessageReject.getExample(); + response = (OASMessageReject) api.v1OrdersCancelAllPost(params); + System.assertEquals(expectedResponse, response); + } + + /** + * Cancel order request + * + * Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + */ + @isTest + private static void v1OrdersCancelPostTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'oaSOrderCancelSingleRequest' => '' + }; + + OASClient client; + OASOrdersApi api; + OASOrderExecutionReport response; + OASOrderExecutionReport expectedResponse; + String js = ''; + + api = new OASOrdersApi(new OASClient()); + + js = JSON.serialize(OASOrderExecutionReport.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = OASOrderExecutionReport.getExample(); + response = (OASOrderExecutionReport) api.v1OrdersCancelPost(params); + System.assertEquals(expectedResponse, response); + } + + /** + * Get open orders + * + * Get last execution reports for open orders across all or single exchange. + */ + @isTest + private static void v1OrdersGetTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'exchangeId' => KRAKEN + }; + + OASClient client; + OASOrdersApi api; + List response; + List expectedResponse; + String js = ''; + + api = new OASOrdersApi(new OASClient()); + + js = JSON.serialize(List.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = List.getExample(); + response = (List) api.v1OrdersGet(params); + System.assertEquals(expectedResponse, response); + } + + /** + * Send new order + * + * This request creating new order for the specific exchange. + */ + @isTest + private static void v1OrdersPostTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'oaSOrderNewSingleRequest' => '' + }; + + OASClient client; + OASOrdersApi api; + OASOrderExecutionReport response; + OASOrderExecutionReport expectedResponse; + String js = ''; + + api = new OASOrdersApi(new OASClient()); + + js = JSON.serialize(OASOrderExecutionReport.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = OASOrderExecutionReport.getExample(); + response = (OASOrderExecutionReport) api.v1OrdersPost(params); + System.assertEquals(expectedResponse, response); + } + + /** + * Get order execution report + * + * Get the last order execution report for the specified order. The requested order does not need to be active or opened. + */ + @isTest + private static void v1OrdersStatusClientOrderIdGetTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'clientOrderId' => 6ab36bc1-344d-432e-ac6d-0bf44ee64c2b + }; + + OASClient client; + OASOrdersApi api; + OASOrderExecutionReport response; + OASOrderExecutionReport expectedResponse; + String js = ''; + + api = new OASOrdersApi(new OASClient()); + + js = JSON.serialize(OASOrderExecutionReport.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = OASOrderExecutionReport.getExample(); + response = (OASOrderExecutionReport) api.v1OrdersStatusClientOrderIdGet(params); + System.assertEquals(expectedResponse, response); + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASOrdersApiTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls new file mode 100644 index 0000000000..3da181a09a --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls @@ -0,0 +1,64 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASPosition + */ +public class OASPosition implements OAS.MappedProperties { + /** + * Exchange identifier used to identify the routing destination. + * @return exchangeId + */ + public String exchangeId { get; set; } + + /** + * Get data + * @return data + */ + public List data { get; set; } + + private static final Map propertyMappings = new Map{ + 'exchange_id' => 'exchangeId' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public OASPosition() { + data = new List(); + } + + public static OASPosition getExample() { + OASPosition position = new OASPosition(); + position.exchangeId = 'KRAKEN'; + position.data = new List{OASPositionData.getExample()}; + return position; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASPosition) { + OASPosition position = (OASPosition) obj; + return this.exchangeId == position.exchangeId + && this.data == position.data; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (exchangeId == null ? 0 : System.hashCode(exchangeId)); + hashCode = (17 * hashCode) + (data == null ? 0 : System.hashCode(data)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPosition.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls new file mode 100644 index 0000000000..28e3fb84d9 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls @@ -0,0 +1,222 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * The Position object. + */ +public class OASPositionData implements OAS.MappedProperties { + /** + * Exchange symbol. + * @return symbolIdExchange + */ + public String symbolIdExchange { get; set; } + + /** + * CoinAPI symbol. + * @return symbolIdCoinapi + */ + public String symbolIdCoinapi { get; set; } + + /** + * Calculated average price of all fills on this position. + * @return avgEntryPrice + */ + public Double avgEntryPrice { get; set; } + + /** + * The current position quantity. + * @return quantity + */ + public Double quantity { get; set; } + + /** + * Get side + * @return side + */ + public OASOrdSide side { get; set; } + + /** + * Unrealised profit or loss (PNL) of this position. + * @return unrealizedPnl + */ + public Double unrealizedPnl { get; set; } + + /** + * Leverage for this position reported by the exchange. + * @return leverage + */ + public Double leverage { get; set; } + + /** + * Is cross margin mode enable for this position? + * @return crossMargin + */ + public Boolean crossMargin { get; set; } + + /** + * Liquidation price. If mark price will reach this value, the position will be liquidated. + * @return liquidationPrice + */ + public Double liquidationPrice { get; set; } + + /** + * Get rawData + * @return rawData + */ + public Object rawData { get; set; } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + private static final Map propertyMappings = new Map{ + 'symbol_id_exchange' => 'symbolIdExchange', + 'symbol_id_coinapi' => 'symbolIdCoinapi', + 'avg_entry_price' => 'avgEntryPrice', + 'unrealized_pnl' => 'unrealizedPnl', + 'cross_margin' => 'crossMargin', + 'liquidation_price' => 'liquidationPrice', + 'raw_data' => 'rawData' + }; + + public Map getPropertyMappings() { + return propertyMappings; + } + + public static OASPositionData getExample() { + OASPositionData positionData = new OASPositionData(); + positionData.symbolIdExchange = 'XBTUSD'; + positionData.symbolIdCoinapi = 'BITMEX_PERP_BTC_USD'; + positionData.avgEntryPrice = 0.00134444; + positionData.quantity = 7; + positionData.side = OASOrdSide.getExample(); + positionData.unrealizedPnl = 0.0; + positionData.leverage = 0.0; + positionData.crossMargin = true; + positionData.liquidationPrice = 0.072323; + positionData.rawData = Other information provided by the exchange on this position.; + return positionData; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASPositionData) { + OASPositionData positionData = (OASPositionData) obj; + return this.symbolIdExchange == positionData.symbolIdExchange + && this.symbolIdCoinapi == positionData.symbolIdCoinapi + && this.avgEntryPrice == positionData.avgEntryPrice + && this.quantity == positionData.quantity + && this.side == positionData.side + && this.unrealizedPnl == positionData.unrealizedPnl + && this.leverage == positionData.leverage + && this.crossMargin == positionData.crossMargin + && this.liquidationPrice == positionData.liquidationPrice + && this.rawData == positionData.rawData; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (symbolIdExchange == null ? 0 : System.hashCode(symbolIdExchange)); + hashCode = (17 * hashCode) + (symbolIdCoinapi == null ? 0 : System.hashCode(symbolIdCoinapi)); + hashCode = (17 * hashCode) + (avgEntryPrice == null ? 0 : System.hashCode(avgEntryPrice)); + hashCode = (17 * hashCode) + (quantity == null ? 0 : System.hashCode(quantity)); + hashCode = (17 * hashCode) + (side == null ? 0 : System.hashCode(side)); + hashCode = (17 * hashCode) + (unrealizedPnl == null ? 0 : System.hashCode(unrealizedPnl)); + hashCode = (17 * hashCode) + (leverage == null ? 0 : System.hashCode(leverage)); + hashCode = (17 * hashCode) + (crossMargin == null ? 0 : System.hashCode(crossMargin)); + hashCode = (17 * hashCode) + (liquidationPrice == null ? 0 : System.hashCode(liquidationPrice)); + hashCode = (17 * hashCode) + (rawData == null ? 0 : System.hashCode(rawData)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionData.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls new file mode 100644 index 0000000000..03b5cdcc9d --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls @@ -0,0 +1,84 @@ +@isTest +private class OASPositionDataTest { + @isTest + private static void equalsSameInstance() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = positionData1; + OASPositionData positionData3 = new OASPositionData(); + OASPositionData positionData4 = positionData3; + + System.assert(positionData1.equals(positionData2)); + System.assert(positionData2.equals(positionData1)); + System.assert(positionData1.equals(positionData1)); + System.assert(positionData3.equals(positionData4)); + System.assert(positionData4.equals(positionData3)); + System.assert(positionData3.equals(positionData3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = OASPositionData.getExample(); + OASPositionData positionData3 = new OASPositionData(); + OASPositionData positionData4 = new OASPositionData(); + + System.assert(positionData1.equals(positionData2)); + System.assert(positionData2.equals(positionData1)); + System.assert(positionData3.equals(positionData4)); + System.assert(positionData4.equals(positionData3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = new OASPositionData(); + + System.assertEquals(false, positionData1.equals('foo')); + System.assertEquals(false, positionData2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = new OASPositionData(); + OASPositionData positionData3; + + System.assertEquals(false, positionData1.equals(positionData3)); + System.assertEquals(false, positionData2.equals(positionData3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = new OASPositionData(); + + System.assertEquals(positionData1.hashCode(), positionData1.hashCode()); + System.assertEquals(positionData2.hashCode(), positionData2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASPositionData positionData1 = OASPositionData.getExample(); + OASPositionData positionData2 = OASPositionData.getExample(); + OASPositionData positionData3 = new OASPositionData(); + OASPositionData positionData4 = new OASPositionData(); + + System.assert(positionData1.equals(positionData2)); + System.assert(positionData3.equals(positionData4)); + System.assertEquals(positionData1.hashCode(), positionData2.hashCode()); + System.assertEquals(positionData3.hashCode(), positionData4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASPositionData positionData = new OASPositionData(); + Map x-property-mappings = positionData.getx-property-mappings(); + System.assertEquals('symbolIdExchange', x-property-mappings.get('symbol_id_exchange')); + System.assertEquals('symbolIdCoinapi', x-property-mappings.get('symbol_id_coinapi')); + System.assertEquals('avgEntryPrice', x-property-mappings.get('avg_entry_price')); + System.assertEquals('unrealizedPnl', x-property-mappings.get('unrealized_pnl')); + System.assertEquals('crossMargin', x-property-mappings.get('cross_margin')); + System.assertEquals('liquidationPrice', x-property-mappings.get('liquidation_price')); + System.assertEquals('rawData', x-property-mappings.get('raw_data')); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionDataTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls new file mode 100644 index 0000000000..38c703fd9e --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls @@ -0,0 +1,85 @@ +@isTest +private class OASPositionTest { + @isTest + private static void equalsSameInstance() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = position1; + OASPosition position3 = new OASPosition(); + OASPosition position4 = position3; + + System.assert(position1.equals(position2)); + System.assert(position2.equals(position1)); + System.assert(position1.equals(position1)); + System.assert(position3.equals(position4)); + System.assert(position4.equals(position3)); + System.assert(position3.equals(position3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = OASPosition.getExample(); + OASPosition position3 = new OASPosition(); + OASPosition position4 = new OASPosition(); + + System.assert(position1.equals(position2)); + System.assert(position2.equals(position1)); + System.assert(position3.equals(position4)); + System.assert(position4.equals(position3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = new OASPosition(); + + System.assertEquals(false, position1.equals('foo')); + System.assertEquals(false, position2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = new OASPosition(); + OASPosition position3; + + System.assertEquals(false, position1.equals(position3)); + System.assertEquals(false, position2.equals(position3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = new OASPosition(); + + System.assertEquals(position1.hashCode(), position1.hashCode()); + System.assertEquals(position2.hashCode(), position2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASPosition position1 = OASPosition.getExample(); + OASPosition position2 = OASPosition.getExample(); + OASPosition position3 = new OASPosition(); + OASPosition position4 = new OASPosition(); + + System.assert(position1.equals(position2)); + System.assert(position3.equals(position4)); + System.assertEquals(position1.hashCode(), position2.hashCode()); + System.assertEquals(position3.hashCode(), position4.hashCode()); + } + + @isTest + private static void maintainRenamedProperties() { + OASPosition position = new OASPosition(); + Map x-property-mappings = position.getx-property-mappings(); + System.assertEquals('exchangeId', x-property-mappings.get('exchange_id')); + } + + @isTest + private static void defaultValuesPopulated() { + OASPosition position = new OASPosition(); + System.assertEquals(new List(), position.data); + System.assertEquals(null, position.exchangeId); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls new file mode 100644 index 0000000000..4afe2a2887 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls @@ -0,0 +1,54 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +public class OASPositionsApi { + OASClient client; + + public OASPositionsApi(OASClient client) { + this.client = client; + } + + public OASPositionsApi() { + this.client = new OASClient(); + } + + public OASClient getClient() { + return this.client; + } + + /** + * Get open positions + * Get current open positions across all or single exchange. + * @param exchangeId Filter the balances to the specific exchange. (optional) + * @return List + * @throws OAS.ApiException if fails to make API call + */ + public List v1PositionsGet(Map params) { + List query = new List(); + + // cast query params to verify their expected type + query.addAll(client.makeParam('exchange_id', (String) params.get('exchangeId'))); + + List form = new List(); + + return (List) client.invoke( + 'GET', '/v1/positions', '', + query, form, + new Map(), + new Map(), + new List{ 'application/json', 'appliction/json' }, + new List(), + new List(), + List.class + ); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApi.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls new file mode 100644 index 0000000000..1d90346eff --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls @@ -0,0 +1,34 @@ +@isTest +private class OASPositionsApiTest { + /** + * Get open positions + * + * Get current open positions across all or single exchange. + */ + @isTest + private static void v1PositionsGetTest() { + HttpResponse res = new HttpResponse(); + res.setStatusCode(200); + res.setStatus('OK'); + Test.setMock(HttpCalloutMock.class, new OASResponseMock(res)); + + Map params = new Map{ + 'exchangeId' => KRAKEN + }; + + OASClient client; + OASPositionsApi api; + List response; + List expectedResponse; + String js = ''; + + api = new OASPositionsApi(new OASClient()); + + js = JSON.serialize(List.getExample()); + res.setHeader('Content-Type', 'application/json'); + res.setBody(js); + expectedResponse = List.getExample(); + response = (List) api.v1PositionsGet(params); + System.assertEquals(expectedResponse, response); + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASPositionsApiTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls new file mode 100644 index 0000000000..dadd91ab86 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls @@ -0,0 +1,25 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Cause of rejection. + */ +public enum OASRejectReason { + OTHER, + EXCHANGE_UNREACHABLE, + EXCHANGE_RESPONSE_TIMEOUT, + ORDER_ID_NOT_FOUND, + INVALID_TYPE, + METHOD_NOT_SUPPORTED, + JSON_ERROR +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReason.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls new file mode 100644 index 0000000000..8e03568e10 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls @@ -0,0 +1,17 @@ +@isTest +private class OASRejectReasonTest { + @isTest + private static void allowableValues() { + Set expected = new Set{ + OASRejectReason.OTHER, + OASRejectReason.EXCHANGE_UNREACHABLE, + OASRejectReason.EXCHANGE_RESPONSE_TIMEOUT, + OASRejectReason.ORDER_ID_NOT_FOUND, + OASRejectReason.INVALID_TYPE, + OASRejectReason.METHOD_NOT_SUPPORTED, + OASRejectReason.JSON_ERROR + }; + Set actual = new Set(OASRejectReason.values()); + System.assertEquals(expected, actual); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASRejectReasonTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls new file mode 100644 index 0000000000..a6931145c5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls @@ -0,0 +1,18 @@ +@isTest +public class OASResponseMock implements HttpCalloutMock { + private final HttpResponse response; + private HttpRequest request; + + public OASResponseMock(HttpResponse response) { + this.response = response; + } + + public HttpResponse respond(HttpRequest request) { + this.request = request; + return response; + } + + public HttpRequest getRequest() { + return request; + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASResponseMock.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls new file mode 100644 index 0000000000..e1c73d185e --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls @@ -0,0 +1,367 @@ +@isTest +private class OASTest { + @isTest + private static void Param_urlEncodeKeyValuePairUtf8() { + String toEncodeLeft = 'Hello +%-_.!~*\'()@'; + String toEncodeRight = 'World +%-_.!~*\'()@'; + String expected = 'Hello+%2B%25-_.%21%7E*%27%28%29%40=World+%2B%25-_.%21%7E*%27%28%29%40'; + String result = new OAS.Param(toEncodeLeft, toEncodeRight).toString(); + System.assertEquals(expected, result); + } + + @isTest + private static void ApiKeyHeaderAuth_keyInHeaderWithGivenName() { + Map headers = new Map(); + List query = new List(); + OAS.ApiKeyHeaderAuth auth = new OAS.ApiKeyHeaderAuth('X-Authenticate'); + auth.setApiKey('foo-bar-api-key'); + auth.apply(headers, query); + + System.assert(query.isEmpty()); + System.assertEquals(1, headers.size()); + System.assertEquals('foo-bar-api-key', headers.get('X-Authenticate')); + } + + @isTest + private static void ApiKeyQueryAuth_keyInQueryParamWithGivenName() { + Map headers = new Map(); + List query = new List(); + OAS.ApiKeyQueryAuth auth = new OAS.ApiKeyQueryAuth('auth_token'); + auth.setApiKey('foo-bar-api-key'); + auth.apply(headers, query); + + System.assert(headers.isEmpty()); + System.assertEquals(1, query.size()); + System.assertEquals('auth_token=foo-bar-api-key', query.get(0).toString()); + } + + @isTest + private static void ApiClient_returnAuthenticationMatchingInput() { + MockApiClient client = new MockApiClient(); + OAS.ApiKeyHeaderAuth auth1 = new OAS.ApiKeyHeaderAuth('foo'); + OAS.ApiKeyQueryAuth auth2 = new OAS.ApiKeyQueryAuth('foo'); + + client.authentications.put('auth1', auth1); + client.authentications.put('auth2', auth2); + + System.assertEquals(auth1, client.getAuthentication('auth1')); + System.assertEquals(auth2, client.getAuthentication('auth2')); + } + + @isTest + private static void ApiClient_oneKeyValuePairForEachValueInList() { + List values = new List{'bar', 4, false, 12.4, ''}; + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParams('foo', values); + + System.assertEquals(5, params.size()); + System.assertEquals('foo=bar', params.get(0).toString()); + System.assertEquals('foo=4', params.get(1).toString()); + System.assertEquals('foo=false', params.get(2).toString()); + System.assertEquals('foo=12.4', params.get(3).toString()); + System.assertEquals('foo=', params.get(4).toString()); + } + + @isTest + private static void ApiClient_nullMultiValuesListToEmptyParamsList() { + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParams('foo', null); + + System.assert(params.isEmpty()); + } + + @isTest + private static void ApiClient_valuesListToSingleCsvKeyValuePair() { + List values = new List{'bar', 4, false, 12.4, ''}; + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParam('foo', values, 'csv'); + + System.assertEquals(1, params.size()); + System.assertEquals('foo=bar%2C4%2Cfalse%2C12.4%2C', params.get(0).toString()); + } + + @isTest + private static void ApiClient_valuesListToSingleSsvKeyValuePair() { + List values = new List{'bar', 4, false, 12.4, ''}; + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParam('foo', values, 'ssv'); + + System.assertEquals(1, params.size()); + System.assertEquals('foo=bar+4+false+12.4+', params.get(0).toString()); + } + + @isTest + private static void ApiClient_valuesListToSingleTsvKeyValuePair() { + List values = new List{'bar', 4, false, 12.4, ''}; + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParam('foo', values, 'tsv'); + + System.assertEquals(1, params.size()); + System.assertEquals('foo=bar%094%09false%0912.4%09', params.get(0).toString()); + } + + @isTest + private static void ApiClient_valuesListToSinglePipeSeparatedKeyValuePair() { + List values = new List{'bar', 4, false, 12.4, ''}; + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParam('foo', values, 'pipes'); + + System.assertEquals(1, params.size()); + System.assertEquals('foo=bar%7C4%7Cfalse%7C12.4%7C', params.get(0).toString()); + } + + @isTest + private static void ApiClient_nullValuesListToEmptyParamsList() { + OAS.ApiClient client = new OAS.ApiClient(); + List params = client.makeParam('foo', null, 'csv'); + + System.assert(params.isEmpty()); + } + + @isTest + private static void ApiClient_paramsFromAnyPrimitiveTypeDiscardNull() { + OAS.ApiClient client = new OAS.ApiClient(); + List params = new List(); + params.addAll(client.makeParam('foo', 'bar')); + params.addAll(client.makeParam('foo', 10)); + params.addAll(client.makeParam('foo', 12.6)); + params.addAll(client.makeParam('foo', true)); + params.addAll(client.makeParam('foo', '')); + params.addAll(client.makeParam('foo', Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0))); + params.addAll(client.makeParam('foo', null)); + + System.assertEquals(6, params.size()); + System.assertEquals('foo=bar', params.get(0).toString()); + System.assertEquals('foo=10', params.get(1).toString()); + System.assertEquals('foo=12.6', params.get(2).toString()); + System.assertEquals('foo=true', params.get(3).toString()); + System.assertEquals('foo=', params.get(4).toString()); + System.assertEquals('foo=2017-01-01+15%3A00%3A00', params.get(5).toString()); + } + + @isTest + private static void ApiClient_requiredParameterPasses() { + OAS.ApiClient client = new OAS.ApiClient(); + client.assertNotNull('foo', 'bar'); + } + + @isTest + private static void ApiClient_requiredParameterFails() { + OAS.ApiClient client = new OAS.ApiClient(); + try { + client.assertNotNull(null, 'bar'); + } catch (NullPointerException e) { + System.assertEquals('Argument cannot be null: bar', e.getMessage()); + return; + } + System.assert(false); + } + + @isTest + private static void ApiClient_extractHeadersFromResponse() { + HttpResponse res = new HttpResponse(); + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Cache-Control', 'private, max-age=0'); + Map headers = new MockApiClient().getHeaders(res); + + System.assertEquals(2, headers.size()); + System.assertEquals('application/json', headers.get('Content-Type')); + System.assertEquals('private, max-age=0', headers.get('Cache-Control')); + } + + @isTest + private static void ApiClient_deserializeResponseBodyByContentType() { + MockApiClient client = new MockApiClient(); + String jsonBody = '{"red":"apple","yellow":"banana","orange":"orange"}'; + Map result1 = (Map) client + .toReturnValue(jsonBody, Map.class, 'application/json'); + + System.assertEquals(3, result1.size()); + System.assertEquals('apple', result1.get('red')); + System.assertEquals('banana', result1.get('yellow')); + System.assertEquals('orange', result1.get('orange')); + + String result2 = (String) client + .toReturnValue('Hello, World!', String.class, 'text/plain'); + + System.assertEquals('Hello, World!', result2); + } + + @isTest + private static void ApiClient_addStringifiedHeadersToRequest() { + MockApiClient client = new MockApiClient(); + Map headers = new Map{ + 'Content-Type' => 'application/json', + 'Max-Forwards' => 10 + }; + HttpRequest req = new HttpRequest(); + client.setHeaders(req, headers); + + System.assertEquals('application/json', req.getHeader('Content-Type')); + System.assertEquals('10', req.getHeader('Max-Forwards')); + } + + @isTest + private static void ApiClient_serializeRequestBodyOrFormByContentType() { + MockApiClient client = new MockApiClient(); + Map body1 = new Map{ + 'hello' => 'world', + 'foo' => 15, + 'bar' => Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0), + 'bat' => false + }; + Set expected1 = new Set{ + '"hello":"world"', + '"foo":15', + '"bar":"2017-01-01T15:00:00.000Z"', + '"bat":false' + }; + Set actual1 = new Set(client + .toBody('application/json', body1, new List()) + .removeStart('{') + .removeEnd('}') + .split(',') + ); + System.assertEquals(expected1, actual1); + + String body2 = 'Hello, World!'; + String actual2 = client.toBody('text/plain', body2, new List()); + System.assertEquals(body2, actual2); + + List form = new List{ + new OAS.Param('hello', 'world'), + new OAS.Param('date', '2017-01-01 15:00:00') + }; + String expected3 = 'hello=world&date=2017-01-01+15%3A00%3A00'; + String actual3 = client.toBody('application/x-www-form-urlencoded', '', form); + System.assertEquals(expected3, actual3); + } + + @isTest + private static void ApiClient_usePreferredContentTypeOrFirstInList() { + MockApiClient client = new MockApiClient(); + + Map headers1 = new Map(); + List types1 = new List{'application/xml', 'application/json', 'text/plain'}; + String result1 = client.setContentTypeHeader(types1, headers1); + System.assertEquals(1, headers1.size()); + System.assertEquals('application/json', headers1.get('Content-Type')); + System.assertEquals('application/json', result1); + + Map headers2 = new Map(); + List types2 = new List{'application/xml', 'text/plain'}; + String result2 = client.setContentTypeHeader(types2, headers2); + System.assertEquals(1, headers2.size()); + System.assertEquals('application/xml', headers2.get('Content-Type')); + System.assertEquals('application/xml', result2); + + Map headers3 = new Map(); + String result3 = client.setContentTypeHeader(new List(), headers3); + System.assertEquals(1, headers3.size()); + System.assertEquals('application/json', headers3.get('Content-Type')); + System.assertEquals('application/json', result3); + } + + @isTest + private static void ApiClient_usePreferredAcceptOrAllInListNoDefault() { + MockApiClient client = new MockApiClient(); + + Map headers1 = new Map(); + List types1 = new List{'application/xml', 'application/json', 'text/plain'}; + client.setAcceptHeader(types1, headers1); + System.assertEquals(1, headers1.size()); + System.assertEquals('application/json', headers1.get('Accept')); + + Map headers2 = new Map(); + List types2 = new List{'application/xml', 'text/plain'}; + client.setAcceptHeader(types2, headers2); + System.assertEquals(1, headers2.size()); + System.assertEquals('application/xml,text/plain', headers2.get('Accept')); + + Map headers3 = new Map(); + client.setAcceptHeader(new List(), headers3); + System.assert(headers3.isEmpty()); + } + + @isTest + private static void ApiClient_formUrlWithQueryParamsPathParams() { + MockApiClient client = new MockApiClient(); + String path = '/departments/{department}'; + Map params = new Map{'department' => 'finance'}; + List queryParams = new List{ + new OAS.Param('foo', 'bar'), + new OAS.Param('bat', '123') + }; + String expected = 'callout:Winkelmeyer/departments/finance?foo=bar&bat=123'; + String actual = client.toEndpoint(path, params, queryParams); + System.assertEquals(expected, actual); + } + + @isTest + private static void ApiClient_returnParsedBody() { + MockApiClient client = new MockApiClient(); + HttpResponse res = new HttpResponse(); + OASResponseMock mock = new OASResponseMock(res); + Test.setMock(HttpCalloutMock.class, mock); + + res.setStatus('OK'); + res.setStatusCode(200); + res.setHeader('Content-Type', 'application/json'); + res.setBody('{' + + '"city":"Austin","country":"United States","latitude":30.28403639999999,' + + '"longitude":-97.73789449999998,"postalCode":"78705","state":"Texas",' + + '"street":"2110 Speedway"}'); + + Address a = (Address) client.invoke( + 'GET', '/address', '', + new List(), + new List(), + new Map(), + new Map(), + new List{'application/json'}, + new List{'text/plain'}, + new List(), + Address.class + ); + + System.assertEquals('Austin', a.getCity()); + System.assertEquals('United States', a.getCountry()); + System.assertEquals(30.28403639999999, a.getLatitude()); + System.assertEquals(-97.73789449999998, a.getLongitude()); + System.assertEquals('78705', a.getPostalCode()); + System.assertEquals('Texas', a.getState()); + System.assertEquals('2110 Speedway', a.getStreet()); + } + + @isTest + private static void ApiClient_noReturnTypeReturnsNull() { + MockApiClient client = new MockApiClient(); + HttpResponse res = new HttpResponse(); + OASResponseMock mock = new OASResponseMock(res); + Test.setMock(HttpCalloutMock.class, mock); + + res.setStatus('OK'); + res.setStatusCode(200); + + Object o = client.invoke( + 'POST', '/address', '', + new List(), + new List(), + new Map(), + new Map(), + new List{'application/json'}, + new List{'text/plain'}, + new List(), + null + ); + + System.assertEquals(null, o); + } + + private class MockApiClient extends OAS.ApiClient { + public MockApiClient() { + basePath = 'https://blog.winkelmeyer.com'; + calloutName = 'Winkelmeyer'; + } + } +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls new file mode 100644 index 0000000000..365c6b03be --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls @@ -0,0 +1,23 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * Order time in force options are documented in the separate section: EMS / Starter Guide / Order parameters / Time in force\n + */ +public enum OASTimeInForce { + GOOD_TILL_CANCEL, + GOOD_TILL_TIME_EXCHANGE, + GOOD_TILL_TIME_OMS, + FILL_OR_KILL, + IMMEDIATE_OR_CANCEL +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForce.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls new file mode 100644 index 0000000000..ed14e4448f --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls @@ -0,0 +1,15 @@ +@isTest +private class OASTimeInForceTest { + @isTest + private static void allowableValues() { + Set expected = new Set{ + OASTimeInForce.GOOD_TILL_CANCEL, + OASTimeInForce.GOOD_TILL_TIME_EXCHANGE, + OASTimeInForce.GOOD_TILL_TIME_OMS, + OASTimeInForce.FILL_OR_KILL, + OASTimeInForce.IMMEDIATE_OR_CANCEL + }; + Set actual = new Set(OASTimeInForce.values()); + System.assertEquals(expected, actual); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASTimeInForceTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls new file mode 100644 index 0000000000..46c631c83e --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls @@ -0,0 +1,79 @@ +/* + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.\n
\nThis API is also available in the Postman application: https://postman.coinapi.io/ \n

\nImplemented Standards:\n\n * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945)\n * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616)\n * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)\n \n### Endpoints\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
\n\n### Authentication\nIf the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. \n

\nIf the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one:\n\n 1. Custom authorization header named `X-CoinAPI-Key` with the API Key\n 2. Query string parameter named `apikey` with the API Key\n 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us.\n\n#### Custom authorization header\nYou can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:\n

\n`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY`\n\n#### Query string authorization parameter\nYou can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request.\nAssuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: \n

\n`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY`\n\n + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by the OAS code generator program. + * https://github.com/OpenAPITools/openapi-generator + * Do not edit the class manually. + */ + +/** + * OASValidationError + */ +public class OASValidationError { + /** + * Get type + * @return type + */ + public String type { get; set; } + + /** + * Get title + * @return title + */ + public String title { get; set; } + + /** + * Get status + * @return status + */ + public Double status { get; set; } + + /** + * Get traceId + * @return traceId + */ + public String traceId { get; set; } + + /** + * Get errors + * @return errors + */ + public String errors { get; set; } + + public static OASValidationError getExample() { + OASValidationError validationError = new OASValidationError(); + validationError.type = 'https://tools.ietf.org/html/rfc7231#section-6.5.1'; + validationError.title = 'One or more validation errors occurred.'; + validationError.status = 400; + validationError.traceId = 'd200e8b5-4271a5461ce5342f'; + validationError.errors = ''; + return validationError; + } + + public Boolean equals(Object obj) { + if (obj instanceof OASValidationError) { + OASValidationError validationError = (OASValidationError) obj; + return this.type == validationError.type + && this.title == validationError.title + && this.status == validationError.status + && this.traceId == validationError.traceId + && this.errors == validationError.errors; + } + return false; + } + + public Integer hashCode() { + Integer hashCode = 43; + hashCode = (17 * hashCode) + (type == null ? 0 : System.hashCode(type)); + hashCode = (17 * hashCode) + (title == null ? 0 : System.hashCode(title)); + hashCode = (17 * hashCode) + (status == null ? 0 : System.hashCode(status)); + hashCode = (17 * hashCode) + (traceId == null ? 0 : System.hashCode(traceId)); + hashCode = (17 * hashCode) + (errors == null ? 0 : System.hashCode(errors)); + return hashCode; + } +} + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationError.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls new file mode 100644 index 0000000000..5418ad808a --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls @@ -0,0 +1,71 @@ +@isTest +private class OASValidationErrorTest { + @isTest + private static void equalsSameInstance() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = validationError1; + OASValidationError validationError3 = new OASValidationError(); + OASValidationError validationError4 = validationError3; + + System.assert(validationError1.equals(validationError2)); + System.assert(validationError2.equals(validationError1)); + System.assert(validationError1.equals(validationError1)); + System.assert(validationError3.equals(validationError4)); + System.assert(validationError4.equals(validationError3)); + System.assert(validationError3.equals(validationError3)); + } + + @isTest + private static void equalsIdenticalInstance() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = OASValidationError.getExample(); + OASValidationError validationError3 = new OASValidationError(); + OASValidationError validationError4 = new OASValidationError(); + + System.assert(validationError1.equals(validationError2)); + System.assert(validationError2.equals(validationError1)); + System.assert(validationError3.equals(validationError4)); + System.assert(validationError4.equals(validationError3)); + } + + @isTest + private static void notEqualsDifferentType() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = new OASValidationError(); + + System.assertEquals(false, validationError1.equals('foo')); + System.assertEquals(false, validationError2.equals('foo')); + } + + @isTest + private static void notEqualsNull() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = new OASValidationError(); + OASValidationError validationError3; + + System.assertEquals(false, validationError1.equals(validationError3)); + System.assertEquals(false, validationError2.equals(validationError3)); + } + + @isTest + private static void consistentHashCodeValue() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = new OASValidationError(); + + System.assertEquals(validationError1.hashCode(), validationError1.hashCode()); + System.assertEquals(validationError2.hashCode(), validationError2.hashCode()); + } + + @isTest + private static void equalInstancesHaveSameHashCode() { + OASValidationError validationError1 = OASValidationError.getExample(); + OASValidationError validationError2 = OASValidationError.getExample(); + OASValidationError validationError3 = new OASValidationError(); + OASValidationError validationError4 = new OASValidationError(); + + System.assert(validationError1.equals(validationError2)); + System.assert(validationError3.equals(validationError4)); + System.assertEquals(validationError1.hashCode(), validationError2.hashCode()); + System.assertEquals(validationError3.hashCode(), validationError4.hashCode()); + } +} diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls-meta.xml new file mode 100644 index 0000000000..fec71a2669 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/classes/OASValidationErrorTest.cls-meta.xml @@ -0,0 +1,5 @@ + + + 42.0 + Active + diff --git a/ems-cloud-mgmt-sdk/apex/force-app/main/default/namedCredentials/EMS__REST_API.namedCredential-meta.xml b/ems-cloud-mgmt-sdk/apex/force-app/main/default/namedCredentials/EMS__REST_API.namedCredential-meta.xml new file mode 100644 index 0000000000..0504483ba2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/force-app/main/default/namedCredentials/EMS__REST_API.namedCredential-meta.xml @@ -0,0 +1,7 @@ + + + https://ems-gateway-aws-eu-central-1-dev.coinapi.io + Anonymous + NoAuthentication + + \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/apex/sfdx-project.json b/ems-cloud-mgmt-sdk/apex/sfdx-project.json new file mode 100644 index 0000000000..e0fe2f7ab1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/apex/sfdx-project.json @@ -0,0 +1,11 @@ +{ + "packageDirectories": [ + { + "path": "force-app", + "default": true + } + ], + "namespace": "", + "sfdcLoginUrl": "https://login.salesforce.com", + "sourceApiVersion": "42.0" +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/bash/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/bash/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/bash/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/bash/.openapi-generator/FILES new file mode 100644 index 0000000000..8f8b2d6af1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/.openapi-generator/FILES @@ -0,0 +1,26 @@ +.openapi-generator-ignore +Dockerfile +README.md +_client.sh +client.sh +client.sh.bash-completion +docs/Balance.md +docs/BalanceData.md +docs/BalancesApi.md +docs/Fills.md +docs/MessageReject.md +docs/OrdSide.md +docs/OrdStatus.md +docs/OrdType.md +docs/OrderCancelAllRequest.md +docs/OrderCancelSingleRequest.md +docs/OrderExecutionReport.md +docs/OrderExecutionReportAllOf.md +docs/OrderNewSingleRequest.md +docs/OrdersApi.md +docs/Position.md +docs/PositionData.md +docs/PositionsApi.md +docs/RejectReason.md +docs/TimeInForce.md +docs/ValidationError.md diff --git a/ems-cloud-mgmt-sdk/bash/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/bash/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/bash/Dockerfile b/ems-cloud-mgmt-sdk/bash/Dockerfile new file mode 100644 index 0000000000..ed59a3edec --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/Dockerfile @@ -0,0 +1,65 @@ +FROM alpine:3.12.0 + +RUN apk add --update --no-cache curl ca-certificates bash bash-completion zsh curl git vim ncurses util-linux + +ADD client.sh /usr/bin/client.sh +ADD _client.sh /usr/local/share/zsh/site-functions/_client.sh +ADD client.sh.bash-completion /etc/bash-completion.d/client.sh +RUN chmod 755 /usr/bin/client.sh + +# +# Install oh-my-zsh +# +RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" || true + +# +# Enable bash completion +# +RUN echo '\n\ +. /etc/bash_completion\n\ +source /etc/bash-completion.d/client.sh\n\ +' >> ~/.bashrc + +# +# Setup prompt +# +RUN echo 'export PS1="[EMS - REST API] \$ "' >> ~/.bashrc +RUN echo 'export PROMPT="[EMS - REST API] \$ "' >> ~/.zshrc + +# +# Setup a welcome message with basic instruction +# +RUN echo -e 'echo "\ +\n\ +This Docker provides preconfigured environment for running the command\n\ +line REST client for $(tput setaf 6)EMS - REST API$(tput sgr0).\n\ +\n\ +For convenience, you can export the following environment variables:\n\ +\n\ + +\n\ +$(tput setaf 7)Basic usage:$(tput sgr0)\n\ +\n\ +$(tput setaf 3)Print the list of operations available on the service$(tput sgr0)\n\ +$ client.sh -h\n\ +\n\ +$(tput setaf 3)Print the service description$(tput sgr0)\n\ +$ client.sh --about\n\ +\n\ +$(tput setaf 3)Print detailed information about specific operation$(tput sgr0)\n\ +$ client.sh -h\n\ +\n\ +By default you are logged into Zsh with full autocompletion for your REST API,\n\ +but you can switch to Bash, where basic autocompletion is also supported.\n\ +\n\ +"\ +' | tee -a ~/.bashrc ~/.zshrc + +# +# Poormans chsh & cleanup to make image as compact as possible +# + +RUN sed -i 's/root:x:0:0:root:\/root:\/bin\/ash/root:x:0:0:root:\/root:\/bin\/zsh/' /etc/passwd +RUN apk del git vim && rm -f /var/cache/apk/* + +ENTRYPOINT ["/bin/zsh"] diff --git a/ems-cloud-mgmt-sdk/bash/README.md b/ems-cloud-mgmt-sdk/bash/README.md new file mode 100644 index 0000000000..fa250eff89 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/README.md @@ -0,0 +1,139 @@ +# EMS - REST API Bash client + +## Overview + +This is a Bash client script for accessing EMS - REST API service. + +The script uses cURL underneath for making all REST calls. + +## Usage + +```shell +# Make sure the script has executable rights +$ chmod u+x + +# Print the list of operations available on the service +$ ./ -h + +# Print the service description +$ ./ --about + +# Print detailed information about specific operation +$ ./ -h + +# Make GET request +./ --host http://: --accept xml = : + +# Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password + -k -sS --tlsv1.2 --host https:// -u : --accept xml = : + +# Make POST request +$ echo '' | --host --content-type json - + +# Make POST request with simple JSON content, e.g.: +# { +# "key1": "value1", +# "key2": "value2", +# "key3": 23 +# } +$ echo '' | --host --content-type json key1==value1 key2=value2 key3:=23 - + +# Make POST request with form data +$ --host key1:=value1 key2:=value2 key3:=23 + +# Preview the cURL command without actually executing it +$ --host http://: --dry-run + +``` + +## Docker image + +You can easily create a Docker image containing a preconfigured environment +for using the REST Bash client including working autocompletion and short +welcome message with basic instructions, using the generated Dockerfile: + +```shell +docker build -t my-rest-client . +docker run -it my-rest-client +``` + +By default you will be logged into a Zsh environment which has much more +advanced auto completion, but you can switch to Bash, where basic autocompletion +is also available. + +## Shell completion + +### Bash + +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source .bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp .bash-completion /etc/bash-completion.d/ +``` + +#### OS X + +On OSX you might need to install bash-completion using Homebrew: + +```shell +brew install bash-completion +``` + +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh + +In Zsh, the generated `_` Zsh completion file must be copied to one of the folders under `$FPATH` variable. + +## Documentation for API Endpoints + +All URIs are relative to ** + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*BalancesApi* | [**v1BalancesGet**](docs/BalancesApi.md#v1balancesget) | **GET** /v1/balances | Get balances +*OrdersApi* | [**v1OrdersCancelAllPost**](docs/OrdersApi.md#v1orderscancelallpost) | **POST** /v1/orders/cancel/all | Cancel all orders request +*OrdersApi* | [**v1OrdersCancelPost**](docs/OrdersApi.md#v1orderscancelpost) | **POST** /v1/orders/cancel | Cancel order request +*OrdersApi* | [**v1OrdersGet**](docs/OrdersApi.md#v1ordersget) | **GET** /v1/orders | Get open orders +*OrdersApi* | [**v1OrdersPost**](docs/OrdersApi.md#v1orderspost) | **POST** /v1/orders | Send new order +*OrdersApi* | [**v1OrdersStatusClientOrderIdGet**](docs/OrdersApi.md#v1ordersstatusclientorderidget) | **GET** /v1/orders/status/{client_order_id} | Get order execution report +*PositionsApi* | [**v1PositionsGet**](docs/PositionsApi.md#v1positionsget) | **GET** /v1/positions | Get open positions + + +## Documentation For Models + + - [Balance](docs/Balance.md) + - [BalanceData](docs/BalanceData.md) + - [Fills](docs/Fills.md) + - [MessageReject](docs/MessageReject.md) + - [OrdSide](docs/OrdSide.md) + - [OrdStatus](docs/OrdStatus.md) + - [OrdType](docs/OrdType.md) + - [OrderCancelAllRequest](docs/OrderCancelAllRequest.md) + - [OrderCancelSingleRequest](docs/OrderCancelSingleRequest.md) + - [OrderExecutionReport](docs/OrderExecutionReport.md) + - [OrderExecutionReportAllOf](docs/OrderExecutionReportAllOf.md) + - [OrderNewSingleRequest](docs/OrderNewSingleRequest.md) + - [Position](docs/Position.md) + - [PositionData](docs/PositionData.md) + - [RejectReason](docs/RejectReason.md) + - [TimeInForce](docs/TimeInForce.md) + - [ValidationError](docs/ValidationError.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + diff --git a/ems-cloud-mgmt-sdk/bash/_client.sh b/ems-cloud-mgmt-sdk/bash/_client.sh new file mode 100644 index 0000000000..a89224faa9 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/_client.sh @@ -0,0 +1,362 @@ +#compdef + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! openapi-generator (https://openapi-generator.tech) +# ! FROM OPENAPI SPECIFICATION IN JSON. +# ! +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! +# ! +# ! +# ! Installation: +# ! +# ! Copy the _ file to any directory under FPATH +# ! environment variable (echo $FPATH) +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +typeset -A mime_type_abbreviations +# text/* +mime_type_abbreviations[text]="text/plain" +mime_type_abbreviations[html]="text/html" +mime_type_abbreviations[md]="text/x-markdown" +mime_type_abbreviations[csv]="text/csv" +mime_type_abbreviations[css]="text/css" +mime_type_abbreviations[rtf]="text/rtf" +# application/* +mime_type_abbreviations[json]="application/json" +mime_type_abbreviations[xml]="application/xml" +mime_type_abbreviations[yaml]="application/yaml" +mime_type_abbreviations[js]="application/javascript" +mime_type_abbreviations[bin]="application/octet-stream" +mime_type_abbreviations[rdf]="application/rdf+xml" +# image/* +mime_type_abbreviations[jpg]="image/jpeg" +mime_type_abbreviations[png]="image/png" +mime_type_abbreviations[gif]="image/gif" +mime_type_abbreviations[bmp]="image/bmp" +mime_type_abbreviations[tiff]="image/tiff" + +# +# Generate zsh completion string list for abbreviated mime types +# +get_mime_type_completions() { + typeset -a result + result=() + for k in "${(@k)mime_type_abbreviations}"; do + value=$mime_type_abbreviations[${k}] + #echo $value + result+=( "${k}[${value}]" ) + #echo $result + done + echo "$result" +} + +# +# cURL crypto engines completion function +# +_curl_crypto_engine() { + local vals + vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} ) + _describe -t outputs 'engines' vals && return 0 +} + +# +# cURL post data completion functions= +# +_curl_post_data() { + + # don't do anything further if this is raw content + compset -P '=' && _message 'raw content' && return 0 + + # complete filename or stdin for @ syntax + compset -P '*@' && { + local expl + _description files expl stdin + compadd "$expl[@]" - "-" + _files + return 0 + } + + # got a name already? expecting data. + compset -P '*=' && _message 'data value' && return 0 + + # otherwise, name (or @ or =) should be specified + _message 'data name' && return 0 + +} + + +local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output + +# HTTP Arguments +arg_http=(''\ + {-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \ + {-b,--cookie}'[pass data to http server as cookie]:data or file' \ + {-c,--cookie-jar}'[specify cookie file]:file name:_files' \ + {-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \ + '--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \ + '--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \ + {-f,--fail}'[enable failfast behavior for server errors]' \ + '*'{-F,--form}'[add POST form data]:name=content' \ + {-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \ + '*'{-H,--header}'[specify an extra header]:header' \ + '--ignore-content-length[ignore Content-Length header]' \ + {-i,--include}'[include HTTP header in the output]' \ + {-j,--junk-session-cookies}'[discard all session cookies]' \ + {-e,--referer}'[send url as referer]:referer url:_urls' \ + {-L,--location}'[follow Location headers on http 3XX response]' \ + '--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \ + '--max-redirs[set maximum number of redirection followings allowed]:number' \ + {-J,--remote-header-name}'[use Content-Disposition for output file name]' \ + {-O,--remote-name}'[write to filename parsed from url instead of stdout]' \ + '--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \ + '--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \ + ) + +# FTP arguments +arg_ftp=(\ + {-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \ + '--crlf[convert LF to CRLF in upload]' \ + '--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \ + '--disable-epsv[disable use of EPSV for passive FTP transfers]' \ + '--ftp-account[account data (FTP)]:data' \ + '--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \ + '--ftp-create-dirs[create paths remotely if it does not exist]' \ + '--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \ + '--ftp-pasv[use passive mode for the data connection (FTP)]' \ + '--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \ + '--form-string[like --form, but do not parse content]:name=string' \ + '--ftp-pret[send PRET before PASV]' \ + '--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \ + '--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \ + '--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \ + {-l,--list-only}'[list names only when listing directories (FTP)]' \ + {-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \ + '*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \ + ) + +# Other Protocol arguments +arg_other=(\ + '--mail-from[specify From: address]:address' \ + '--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \ + {-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \ + '--tftp-blksize[set tftp BLKSIZE option]:value' \ + ) + +# Proxy arguments +arg_proxy=(\ + '--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \ + {-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \ + {-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \ + '--proxy-anyauth[use any authentication method for proxy, default to most secure]' \ + '--proxy-basic[use HTTP Basic authentication for proxy]' \ + '--proxy-digest[use http digest authentication for proxy]' \ + '--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \ + '--proxy-ntlm[enable ntlm authentication for proxy]' \ + '--proxy1.0[use http 1.0 proxy]:proxy url' \ + {-x,--proxy}'[use specified proxy]:proxy url' \ + '--socks5-gssapi-service[change service name for socks server]:servicename' \ + '--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \ + ) + +# Crypto arguments +arg_crypto=(\ + {-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \ + {-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \ + {-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \ + '--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \ + '--crlfile[specify file with revoked certificates]:file' \ + '--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \ + {-E,--cert}'[use specified client certificate]:certificate file:_files' \ + '--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \ + '--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \ + '--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \ + '--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \ + '--capath[specify a search path for certificate files]:CA certificate directory:_directories' \ + '--hostpubmd5[check remote hosts public key]:md5 hash' \ + {-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \ + '--key[ssl/ssh private key file name]:key file:_files' \ + '--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \ + '--pubkey[ssh public key file]:pubkey file:_files' \ + '--random-file[set source of random data for ssl]:random source:_files' \ + '--no-sessionid[disable caching of ssl session ids]' \ + '--pass:phrase[passphrase for ssl/ssh private key]' \ + '--ssl[try to use ssl/tls for connection, if available]' \ + '--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \ + '--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \ + '--tlsuser[set username for TLS authentication]:user' \ + '--tlspassword[set password for TLS authentication]:password' \ + ) + +# Connection arguments +arg_connection=(\ + {-4,--ipv4}'[prefer ipv4]' \ + {-6,--ipv6}'[prefer ipv6, if available]' \ + {-B,--use-ascii}'[use ascii mode]' \ + '--compressed[request a compressed transfer]' \ + '--connect-timeout[timeout for connection phase]:seconds' \ + {-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \ + '--interface[work on a specific interface]:name' \ + '--keepalive-time[set time to wait before sending keepalive probes]:seconds' \ + '--limit-rate[specify maximum transfer rate]:speed' \ + '--local-port[set preferred number or range of local ports to use]:num' \ + {-N,--no-buffer}'[disable buffering of the output stream]' \ + '--no-keepalive[disable use of keepalive messages in TCP connections]' \ + '--raw[disable all http decoding and pass raw data]' \ + '--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \ + '--retry[specify maximum number of retries for transient errors]:num' \ + '--retry-delay[specify delay between retries]:seconds' \ + '--retry-max-time[maximum time to spend on retries]:seconds' \ + '--tcp-nodelay[turn on TCP_NODELAY option]' \ + {-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \ + {-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \ + ) + +# Authentication arguments +arg_auth=(\ + '--anyauth[use any authentication method, default to most secure]' \ + '--basic[use HTTP Basic authentication]' \ + '--ntlm[enable ntlm authentication]' \ + '--digest[use http digest authentication]' \ + '--krb[use kerberos authentication]:auth:(clear safe confidential private)' \ + '--negotiate[enable GSS-Negotiate authentication]' \ + {-n,--netrc}'[scan ~/.netrc for login data]' \ + '--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \ + '--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \ + '--tr-encoding[request compressed transfer-encoding]' \ + {-u,--user}'[specify user name and password for server authentication]:user\:password' \ + ) + +# Input arguments +arg_input=(\ + {-C,--continue-at}'[resume at offset ]:offset' \ + {-g,--globoff}'[do not glob {}\[\] letters]' \ + '--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \ + '--proto[specify allowed protocols for transfer]:protocols' \ + '--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \ + {-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + {-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \ + '--url[specify a URL to fetch (multi)]:url:_urls' \ + {-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \ + ) + +# Output arguments +arg_output=(\ + '--create-dirs[create local directory hierarchy as needed]' \ + {-D,--dump-header}'[write protocol headers to file]:dump file:_files' \ + {-o,--output}'[write to specified file instead of stdout]:output file:_files' \ + {--progress-bar,-\#}'[display progress as a simple progress bar]' \ + {-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + '--raw[disable all http decoding and pass raw data]' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \ + '--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \ + '--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \ + {-v,--verbose}'[output debug info]' \ + {-w,--write-out}'[specify message to output on successful operation]:format string' \ + '--xattr[store some file metadata in extended file attributes]' \ + {-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \ + ) + +_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ + {-M,--manual}'[Print manual]' \ + '*'{-K,--config}'[Use other config file to read arguments from]:config file:_files' \ + '--libcurl[output libcurl code for the operation to file]:output file:_files' \ + {-m,--max-time}'[Limit total time of operation]:seconds' \ + {-s,--silent}'[Silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[Show errors in silent mode]' \ + '--stderr[Redirect stderr to specified file]:output file:_files' \ + '-q[Do not read settings from .curlrc (must be first option)]' \ + {-h,--help}'[Print help and list of operations]' \ + {-V,--version}'[Print service API version]' \ + '--about[Print the information about service]' \ + '--host[Specify the host URL]':URL:_urls \ + '--dry-run[Print out the cURL command without executing it]' \ + {-ac,--accept}'[Set the Accept header in the request]: :{_values "Accept mime type" $(get_mime_type_completions)}' \ + {-ct,--content-type}'[Set the Content-type header in request]: :{_values "Content mime type" $(get_mime_type_completions)}' \ + '1: :->ops' \ + '*:: :->args' \ + && ret=0 + + +case $state in + ops) + # Operations + _values "Operations" \ + "v1BalancesGet[Get balances]" "v1OrdersCancelAllPost[Cancel all orders request]" \ + "v1OrdersCancelPost[Cancel order request]" \ + "v1OrdersGet[Get open orders]" \ + "v1OrdersPost[Send new order]" \ + "v1OrdersStatusClientOrderIdGet[Get order execution report]" "v1PositionsGet[Get open positions]" \ + + _arguments "(--help)--help[Print information about operation]" + + ret=0 + ;; + args) + case $line[1] in + v1BalancesGet) + local -a _op_arguments + _op_arguments=( + "exchange_id=:[QUERY] Filter the balances to the specific exchange." + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1OrdersCancelAllPost) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1OrdersCancelPost) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1OrdersGet) + local -a _op_arguments + _op_arguments=( + "exchange_id=:[QUERY] Filter the open orders to the specific exchange." + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1OrdersPost) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1OrdersStatusClientOrderIdGet) + local -a _op_arguments + _op_arguments=( + "client_order_id=:[PATH] The unique identifier of the order assigned by the client." + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + v1PositionsGet) + local -a _op_arguments + _op_arguments=( + "exchange_id=:[QUERY] Filter the balances to the specific exchange." + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + esac + ;; + +esac + +return ret diff --git a/ems-cloud-mgmt-sdk/bash/client.sh b/ems-cloud-mgmt-sdk/bash/client.sh new file mode 100644 index 0000000000..9f3b720feb --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/client.sh @@ -0,0 +1,1402 @@ +#!/usr/bin/env bash + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! openapi-generator (https://openapi-generator.tech) +# ! FROM OPENAPI SPECIFICATION IN JSON. +# ! +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# +# This is a Bash client for EMS - REST API. +# +# LICENSE: +# https://github.com/coinapi/coinapi-sdk/blob/master/LICENSE +# +# CONTACT: +# support@coinapi.io +# +# MORE INFORMATION: +# https://docs.coinapi.io/ +# + +# For improved pattern matching in case statements +shopt -s extglob + +############################################################################### +# +# Make sure Bash is at least in version 4.3 +# +############################################################################### +if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ + && ! (("${BASH_VERSION:0:1}" >= "5")); then + echo "" + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + echo "" + exit 1 +fi + +############################################################################### +# +# Global variables +# +############################################################################### + +## +# The filename of this script for help messages +script_name=$(basename "$0") + +## +# Map for headers passed after operation as KEY:VALUE +declare -A header_arguments + + +## +# Map for operation parameters passed after operation as PARAMETER=VALUE +# These will be mapped to appropriate path or query parameters +# The values in operation_parameters are arrays, so that multiple values +# can be provided for the same parameter if allowed by API specification +declare -A operation_parameters + +## +# Declare colors with autodetection if output is terminal +if [ -t 1 ]; then + RED="$(tput setaf 1)" + GREEN="$(tput setaf 2)" + YELLOW="$(tput setaf 3)" + BLUE="$(tput setaf 4)" + MAGENTA="$(tput setaf 5)" + CYAN="$(tput setaf 6)" + WHITE="$(tput setaf 7)" + BOLD="$(tput bold)" + OFF="$(tput sgr0)" +else + RED="" + GREEN="" + YELLOW="" + BLUE="" + MAGENTA="" + CYAN="" + WHITE="" + BOLD="" + OFF="" +fi + +declare -a result_color_table=( "$WHITE" "$WHITE" "$GREEN" "$YELLOW" "$WHITE" "$MAGENTA" "$WHITE" ) + +## +# This array stores the minimum number of required occurrences for parameter +# 0 - optional +# 1 - required +declare -A operation_parameters_minimum_occurrences +operation_parameters_minimum_occurrences["v1BalancesGet:::exchange_id"]=0 +operation_parameters_minimum_occurrences["v1OrdersCancelAllPost:::OrderCancelAllRequest"]=1 +operation_parameters_minimum_occurrences["v1OrdersCancelPost:::OrderCancelSingleRequest"]=1 +operation_parameters_minimum_occurrences["v1OrdersGet:::exchange_id"]=0 +operation_parameters_minimum_occurrences["v1OrdersPost:::OrderNewSingleRequest"]=1 +operation_parameters_minimum_occurrences["v1OrdersStatusClientOrderIdGet:::client_order_id"]=1 +operation_parameters_minimum_occurrences["v1PositionsGet:::exchange_id"]=0 + +## +# This array stores the maximum number of allowed occurrences for parameter +# 1 - single value +# 2 - 2 values +# N - N values +# 0 - unlimited +declare -A operation_parameters_maximum_occurrences +operation_parameters_maximum_occurrences["v1BalancesGet:::exchange_id"]=0 +operation_parameters_maximum_occurrences["v1OrdersCancelAllPost:::OrderCancelAllRequest"]=0 +operation_parameters_maximum_occurrences["v1OrdersCancelPost:::OrderCancelSingleRequest"]=0 +operation_parameters_maximum_occurrences["v1OrdersGet:::exchange_id"]=0 +operation_parameters_maximum_occurrences["v1OrdersPost:::OrderNewSingleRequest"]=0 +operation_parameters_maximum_occurrences["v1OrdersStatusClientOrderIdGet:::client_order_id"]=0 +operation_parameters_maximum_occurrences["v1PositionsGet:::exchange_id"]=0 + +## +# The type of collection for specifying multiple values for parameter: +# - multi, csv, ssv, tsv +declare -A operation_parameters_collection_type +operation_parameters_collection_type["v1BalancesGet:::exchange_id"]="" +operation_parameters_collection_type["v1OrdersCancelAllPost:::OrderCancelAllRequest"]="" +operation_parameters_collection_type["v1OrdersCancelPost:::OrderCancelSingleRequest"]="" +operation_parameters_collection_type["v1OrdersGet:::exchange_id"]="" +operation_parameters_collection_type["v1OrdersPost:::OrderNewSingleRequest"]="" +operation_parameters_collection_type["v1OrdersStatusClientOrderIdGet:::client_order_id"]="" +operation_parameters_collection_type["v1PositionsGet:::exchange_id"]="" + + +## +# Map for body parameters passed after operation as +# PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE +# These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) +declare -A body_parameters + +## +# These arguments will be directly passed to cURL +curl_arguments="" + +## +# The host for making the request +host="" + +## +# The user credentials for basic authentication +basic_auth_credential="" + + +## +# If true, the script will only output the actual cURL command that would be +# used +print_curl=false + +## +# The operation ID passed on the command line +operation="" + +## +# The provided Accept header value +header_accept="" + +## +# The provided Content-type header value +header_content_type="" + +## +# If there is any body content on the stdin pass it to the body of the request +body_content_temp_file="" + +## +# If this variable is set to true, the request will be performed even +# if parameters for required query, header or body values are not provided +# (path parameters are still required). +force=false + +## +# Declare some mime types abbreviations for easier content-type and accepts +# headers specification +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +############################################################################## +# +# Escape special URL characters +# Based on table at http://www.w3schools.com/tags/ref_urlencode.asp +# +############################################################################## +url_escape() { + local raw_url="$1" + + value=$(sed -e 's/ /%20/g' \ + -e 's/!/%21/g' \ + -e 's/"/%22/g' \ + -e 's/#/%23/g' \ + -e 's/\&/%26/g' \ + -e 's/'\''/%28/g' \ + -e 's/(/%28/g' \ + -e 's/)/%29/g' \ + -e 's/:/%3A/g' \ + -e 's/\\t/%09/g' \ + -e 's/?/%3F/g' <<<"$raw_url"); + + echo "$value" +} + +############################################################################## +# +# Lookup the mime type abbreviation in the mime_type_abbreviations array. +# If not present assume the user provided a valid mime type +# +############################################################################## +lookup_mime_type() { + local mime_type="$1" + + if [[ ${mime_type_abbreviations[$mime_type]} ]]; then + echo "${mime_type_abbreviations[$mime_type]}" + else + echo "$mime_type" + fi +} + +############################################################################## +# +# Converts an associative array into a list of cURL header +# arguments (-H "KEY: VALUE") +# +############################################################################## +header_arguments_to_curl() { + local headers_curl="" + + for key in "${!header_arguments[@]}"; do + headers_curl+="-H \"${key}: ${header_arguments[${key}]}\" " + done + headers_curl+=" " + + echo "${headers_curl}" +} + +############################################################################## +# +# Converts an associative array into a simple JSON with keys as top +# level object attributes +# +# \todo Add conversion of more complex attributes using paths +# +############################################################################## +body_parameters_to_json() { + local body_json="-d '{" + local count=0 + for key in "${!body_parameters[@]}"; do + if [[ $((count++)) -gt 0 ]]; then + body_json+=", " + fi + body_json+="\"${key}\": ${body_parameters[${key}]}" + done + body_json+="}'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_json}" + fi +} + +############################################################################## +# +# Converts an associative array into form urlencoded string +# +############################################################################## +body_parameters_to_form_urlencoded() { + local body_form_urlencoded="-d '" + local count=0 + for key in "${!body_parameters[@]}"; do + if [[ $((count++)) -gt 0 ]]; then + body_form_urlencoded+="&" + fi + body_form_urlencoded+="${key}=${body_parameters[${key}]}" + done + body_form_urlencoded+="'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_form_urlencoded}" + fi +} + +############################################################################## +# +# Helper method for showing error because for example echo in +# build_request_path() is evaluated as part of command line not printed on +# output. Anyway better idea for resource clean up ;-). +# +############################################################################## +ERROR_MSG="" +function finish { + if [[ -n "$ERROR_MSG" ]]; then + echo >&2 "${OFF}${RED}$ERROR_MSG" + echo >&2 "${OFF}Check usage: '${script_name} --help'" + fi +} +trap finish EXIT + + +############################################################################## +# +# Validate and build request path including query parameters +# +############################################################################## +build_request_path() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + + # + # Check input parameters count against minimum and maximum required + # + if [[ "$force" = false ]]; then + local was_error="" + for qparam in "${query_params[@]}" "${path_params[@]}"; do + local parameter_values + mapfile -t parameter_values < <(sed -e 's/'":::"'/\n/g' <<<"${operation_parameters[$qparam]}") + + # + # Check if the number of provided values is not less than minimum required + # + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurrences["${operation}:::${qparam}"]} ]]; then + echo "ERROR: Too few values provided for '${qparam}' parameter." + was_error=true + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurrences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurrences["${operation}:::${qparam}"]} ]]; then + echo "ERROR: Too many values provided for '${qparam}' parameter" + was_error=true + fi + done + if [[ -n "$was_error" ]]; then + exit 1 + fi + fi + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + local path_regex="(.*)(\\{$pparam\\})(.*)" + if [[ $path_template =~ $path_regex ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + local query_request_part="" + + for qparam in "${query_params[@]}"; do + if [[ "${operation_parameters[$qparam]}" == "" ]]; then + continue + fi + + # Get the array of parameter values + local parameter_value="" + local parameter_values + mapfile -t parameter_values < <(sed -e 's/'":::"'/\n/g' <<<"${operation_parameters[$qparam]}") + + + + # + # Append parameters without specific cardinality + # + local collection_type="${operation_parameters_collection_type["${operation}:::${qparam}"]}" + if [[ "${collection_type}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + if [[ $((vcount++)) -gt 0 ]]; then + parameter_value+="&" + fi + parameter_value+="${qparam}=${qvalue}" + done + # + # Append parameters specified as 'multi' collections i.e. param=value1¶m=value2&... + # + elif [[ "${collection_type}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + if [[ $((vcount++)) -gt 0 ]]; then + parameter_value+="&" + fi + parameter_value+="${qparam}=${qvalue}" + done + # + # Append parameters specified as 'csv' collections i.e. param=value1,value2,... + # + elif [[ "${collection_type}" == "csv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + if [[ $((vcount++)) -gt 0 ]]; then + parameter_value+="," + fi + parameter_value+="${qvalue}" + done + # + # Append parameters specified as 'ssv' collections i.e. param="value1 value2 ..." + # + elif [[ "${collection_type}" == "ssv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + if [[ $((vcount++)) -gt 0 ]]; then + parameter_value+=" " + fi + parameter_value+="${qvalue}" + done + # + # Append parameters specified as 'tsv' collections i.e. param="value1\tvalue2\t..." + # + elif [[ "${collection_type}" == "tsv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + if [[ $((vcount++)) -gt 0 ]]; then + parameter_value+="\\t" + fi + parameter_value+="${qvalue}" + done + else + echo "Unsupported collection format \"${collection_type}\"" + exit 1 + fi + + if [[ -n "${parameter_value}" ]]; then + if [[ -n "${query_request_part}" ]]; then + query_request_part+="&" + fi + query_request_part+="${parameter_value}" + fi + + done + + + # Now append query parameters - if any + if [[ -n "${query_request_part}" ]]; then + path_template+="?${query_request_part}" + fi + + echo "$path_template" +} + + + +############################################################################### +# +# Print main help message +# +############################################################################### +print_help() { +cat <${OFF}] + [-ac|--accept ${GREEN}${OFF}] [-ct,--content-type ${GREEN}${OFF}] + [--host ${CYAN}${OFF}] [--dry-run] [-nc|--no-colors] ${YELLOW}${OFF} [-h|--help] + [${BLUE}${OFF}] [${MAGENTA}${OFF}] [${MAGENTA}${OFF}] + + - ${CYAN}${OFF} - endpoint of the REST service without basepath + + - ${RED}${OFF} - any valid cURL options can be passed before ${YELLOW}${OFF} + - ${GREEN}${OFF} - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - ${BLUE}${OFF} - HTTP headers can be passed in the form ${YELLOW}HEADER${OFF}:${BLUE}VALUE${OFF} + - ${MAGENTA}${OFF} - REST operation parameters can be passed in the following + forms: + * ${YELLOW}KEY${OFF}=${BLUE}VALUE${OFF} - path or query parameters + - ${MAGENTA}${OFF} - simple JSON body content (first level only) can be build + using the following arguments: + * ${YELLOW}KEY${OFF}==${BLUE}VALUE${OFF} - body parameters which will be added to body + JSON as '{ ..., "${YELLOW}KEY${OFF}": "${BLUE}VALUE${OFF}", ... }' + * ${YELLOW}KEY${OFF}:=${BLUE}VALUE${OFF} - body parameters which will be added to body + JSON as '{ ..., "${YELLOW}KEY${OFF}": ${BLUE}VALUE${OFF}, ... }' + +EOF + echo -e "${BOLD}${WHITE}Operations (grouped by tags)${OFF}" + echo "" + echo -e "${BOLD}${WHITE}[balances]${OFF}" +read -r -d '' ops <${OFF}\\t\\t\\t\\tSpecify the host URL " +echo -e " \\t\\t\\t\\t(e.g. 'https://ems-gateway-aws-eu-central-1-dev.coinapi.io')" + + echo -e " --force\\t\\t\\t\\tForce command invocation in spite of missing" + echo -e " \\t\\t\\t\\trequired parameters or wrong content type" + echo -e " --dry-run\\t\\t\\t\\tPrint out the cURL command without" + echo -e " \\t\\t\\t\\texecuting it" + echo -e " -nc,--no-colors\\t\\t\\tEnforce print without colors, otherwise autodetected" + echo -e " -ac,--accept ${YELLOW}${OFF}\\t\\tSet the 'Accept' header in the request" + echo -e " -ct,--content-type ${YELLOW}${OFF}\\tSet the 'Content-type' header in " + echo -e " \\tthe request" + echo "" +} + + +############################################################################## +# +# Print REST service description +# +############################################################################## +print_about() { + echo "" + echo -e "${BOLD}${WHITE}EMS - REST API command line client (API version v1)${OFF}" + echo "" + echo -e "License: 28961" + echo -e "Contact: support@coinapi.io" + echo "" +read -r -d '' appdescription < +This API is also available in the Postman application: https://postman.coinapi.io/ +

+Implemented Standards: + + * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) + * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) + * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) + +### Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
+ +### Authentication +If the software is deployed as 'Self-Hosted' then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. +

+If the software is deployed in our 'Managed Cloud', there are 2 methods for authenticating with us, you only need to use one: + + 1. Custom authorization header named 'X-CoinAPI-Key' with the API Key + 2. Query string parameter named 'apikey' with the API Key + 3. TLS Client Certificate from the 'Managed Cloud REST API' (/v1/certificate/pem endpoint) while establishing a TLS session with us. + +#### Custom authorization header +You can authorize by providing additional custom header named 'X-CoinAPI-Key' and API key as its value. +Assuming that your API key is '73034021-THIS-IS-SAMPLE-KEY', then the authorization header you should send to us will look like: +

+'X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY' + +#### Query string authorization parameter +You can authorize by providing an additional parameter named 'apikey' with a value equal to your API key in the query string of your HTTP request. +Assuming that your API key is '73034021-THIS-IS-SAMPLE-KEY' and that you want to request all balances, then your query string should look like this: +

+'GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY' + +EOF +echo "$appdescription" | paste -sd' ' | fold -sw 80 +} + + +############################################################################## +# +# Print REST api version +# +############################################################################## +print_version() { + echo "" + echo -e "${BOLD}EMS - REST API command line client (API version v1)${OFF}" + echo "" +} + +############################################################################## +# +# Print help for v1BalancesGet operation +# +############################################################################## +print_v1BalancesGet_help() { + echo "" + echo -e "${BOLD}${WHITE}v1BalancesGet - Get balances${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "Get current currency balance from all or single exchange." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}exchange_id${OFF} ${BLUE}[string]${OFF} ${CYAN}(default: null)${OFF} - Filter the balances to the specific exchange.${YELLOW} Specify as: exchange_id=value${OFF}" \ + | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;Collection of balances.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1OrdersCancelAllPost operation +# +############################################################################## +print_v1OrdersCancelAllPost_help() { + echo "" + echo -e "${BOLD}${WHITE}v1OrdersCancelAllPost - Cancel all orders request${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "This request cancels all open orders on single specified exchange." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}body${OFF} ${BLUE}[application/json]${OFF} ${RED}(required)${OFF}${OFF} - OrderCancelAllRequest object." | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;Result${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=400 + echo -e "${result_color_table[${code:0:1}]} 400;Input model validation errors.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1OrdersCancelPost operation +# +############################################################################## +print_v1OrdersCancelPost_help() { + echo "" + echo -e "${BOLD}${WHITE}v1OrdersCancelPost - Cancel order request${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "Request cancel for an existing order. The order can be canceled using the 'client_order_id' or 'exchange_order_id'." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}body${OFF} ${BLUE}[application/json]${OFF} ${RED}(required)${OFF}${OFF} - OrderCancelSingleRequest object." | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;The last execution report for the order for which cancelation was requested.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=400 + echo -e "${result_color_table[${code:0:1}]} 400;Input model validation errors.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1OrdersGet operation +# +############################################################################## +print_v1OrdersGet_help() { + echo "" + echo -e "${BOLD}${WHITE}v1OrdersGet - Get open orders${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "Get last execution reports for open orders across all or single exchange." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}exchange_id${OFF} ${BLUE}[string]${OFF} ${CYAN}(default: null)${OFF} - Filter the open orders to the specific exchange.${YELLOW} Specify as: exchange_id=value${OFF}" \ + | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;Collection of order execution reports.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Filtered exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1OrdersPost operation +# +############################################################################## +print_v1OrdersPost_help() { + echo "" + echo -e "${BOLD}${WHITE}v1OrdersPost - Send new order${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "This request creating new order for the specific exchange." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}body${OFF} ${BLUE}[application/json]${OFF} ${RED}(required)${OFF}${OFF} - OrderNewSingleRequest object." | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;Created${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=400 + echo -e "${result_color_table[${code:0:1}]} 400;Input model validation errors.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=504 + echo -e "${result_color_table[${code:0:1}]} 504;Exchange didn't responded in the defined timeout.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1OrdersStatusClientOrderIdGet operation +# +############################################################################## +print_v1OrdersStatusClientOrderIdGet_help() { + echo "" + echo -e "${BOLD}${WHITE}v1OrdersStatusClientOrderIdGet - Get order execution report${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "Get the last order execution report for the specified order. The requested order does not need to be active or opened." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}client_order_id${OFF} ${BLUE}[string]${OFF} ${RED}(required)${OFF} ${CYAN}(default: null)${OFF} - The unique identifier of the order assigned by the client. ${YELLOW}Specify as: client_order_id=value${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;The last execution report of the requested order.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=404 + echo -e "${result_color_table[${code:0:1}]} 404;The requested order was not found.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} +############################################################################## +# +# Print help for v1PositionsGet operation +# +############################################################################## +print_v1PositionsGet_help() { + echo "" + echo -e "${BOLD}${WHITE}v1PositionsGet - Get open positions${OFF}" | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo -e "Get current open positions across all or single exchange." | paste -sd' ' | fold -sw 80 + echo -e "" + echo -e "${BOLD}${WHITE}Parameters${OFF}" + echo -e " * ${GREEN}exchange_id${OFF} ${BLUE}[string]${OFF} ${CYAN}(default: null)${OFF} - Filter the balances to the specific exchange.${YELLOW} Specify as: exchange_id=value${OFF}" \ + | paste -sd' ' | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "${BOLD}${WHITE}Responses${OFF}" + code=200 + echo -e "${result_color_table[${code:0:1}]} 200;Collection of positons.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + code=490 + echo -e "${result_color_table[${code:0:1}]} 490;Exchange is unreachable.${OFF}" | paste -sd' ' | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' +} + + +############################################################################## +# +# Call v1BalancesGet operation +# +############################################################################## +call_v1BalancesGet() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=(exchange_id) + local path + + if ! path=$(build_request_path "/v1/balances" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="GET" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call v1OrdersCancelAllPost operation +# +############################################################################## +call_v1OrdersCancelAllPost() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=() + local path + + if ! path=$(build_request_path "/v1/orders/cancel/all" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="POST" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the OpenAPI specification + # if values produces and consumes are defined unambiguously + # + if [[ -z $header_content_type ]]; then + header_content_type="application/json" + fi + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "ERROR: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\\t- application/json" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call v1OrdersCancelPost operation +# +############################################################################## +call_v1OrdersCancelPost() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=() + local path + + if ! path=$(build_request_path "/v1/orders/cancel" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="POST" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the OpenAPI specification + # if values produces and consumes are defined unambiguously + # + if [[ -z $header_content_type ]]; then + header_content_type="application/json" + fi + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "ERROR: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\\t- application/json" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call v1OrdersGet operation +# +############################################################################## +call_v1OrdersGet() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=(exchange_id) + local path + + if ! path=$(build_request_path "/v1/orders" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="GET" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call v1OrdersPost operation +# +############################################################################## +call_v1OrdersPost() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=() + local path + + if ! path=$(build_request_path "/v1/orders" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="POST" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the OpenAPI specification + # if values produces and consumes are defined unambiguously + # + if [[ -z $header_content_type ]]; then + header_content_type="application/json" + fi + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "ERROR: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\\t- application/json" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call v1OrdersStatusClientOrderIdGet operation +# +############################################################################## +call_v1OrdersStatusClientOrderIdGet() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=(client_order_id) + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=() + local path + + if ! path=$(build_request_path "/v1/orders/status/{client_order_id}" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="GET" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call v1PositionsGet operation +# +############################################################################## +call_v1PositionsGet() { + # ignore error about 'path_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local path_parameter_names=() + # ignore error about 'query_parameter_names' being unused; passed by reference + # shellcheck disable=SC2034 + local query_parameter_names=(exchange_id) + local path + + if ! path=$(build_request_path "/v1/positions" path_parameter_names query_parameter_names); then + ERROR_MSG=$path + exit 1 + fi + local method="GET" + local headers_curl + headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl -d '' ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + + + +############################################################################## +# +# Main +# +############################################################################## + + +# Check dependencies +type curl >/dev/null 2>&1 || { echo >&2 "ERROR: You do not have 'cURL' installed."; exit 1; } +type sed >/dev/null 2>&1 || { echo >&2 "ERROR: You do not have 'sed' installed."; exit 1; } +type column >/dev/null 2>&1 || { echo >&2 "ERROR: You do not have 'bsdmainutils' installed."; exit 1; } + +# +# Process command line +# +# Pass all arguments before 'operation' to cURL except the ones we override +# +take_user=false +take_host=false +take_accept_header=false +take_contenttype_header=false + +for key in "$@"; do +# Take the value of -u|--user argument +if [[ "$take_user" = true ]]; then + basic_auth_credential="$key" + take_user=false + continue +fi +# Take the value of --host argument +if [[ "$take_host" = true ]]; then + host="$key" + take_host=false + continue +fi +# Take the value of --accept argument +if [[ "$take_accept_header" = true ]]; then + header_accept=$(lookup_mime_type "$key") + take_accept_header=false + continue +fi +# Take the value of --content-type argument +if [[ "$take_contenttype_header" = true ]]; then + header_content_type=$(lookup_mime_type "$key") + take_contenttype_header=false + continue +fi +case $key in + -h|--help) + if [[ "x$operation" == "x" ]]; then + print_help + exit 0 + else + eval "print_${operation}_help" + exit 0 + fi + ;; + -V|--version) + print_version + exit 0 + ;; + --about) + print_about + exit 0 + ;; + -u|--user) + take_user=true + ;; + --host) + take_host=true + ;; + --force) + force=true + ;; + -ac|--accept) + take_accept_header=true + ;; + -ct|--content-type) + take_contenttype_header=true + ;; + --dry-run) + print_curl=true + ;; + -nc|--no-colors) + RED="" + GREEN="" + YELLOW="" + BLUE="" + MAGENTA="" + CYAN="" + WHITE="" + BOLD="" + OFF="" + result_color_table=( "" "" "" "" "" "" "" ) + ;; + v1BalancesGet) + operation="v1BalancesGet" + ;; + v1OrdersCancelAllPost) + operation="v1OrdersCancelAllPost" + ;; + v1OrdersCancelPost) + operation="v1OrdersCancelPost" + ;; + v1OrdersGet) + operation="v1OrdersGet" + ;; + v1OrdersPost) + operation="v1OrdersPost" + ;; + v1OrdersStatusClientOrderIdGet) + operation="v1OrdersStatusClientOrderIdGet" + ;; + v1PositionsGet) + operation="v1PositionsGet" + ;; + *==*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content as strings + if [[ "$operation" ]]; then + IFS='==' read -r body_key sep body_value <<< "$key" + body_parameters[${body_key}]="\"${body_value}\"" + fi + ;; + *:=*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content without quotes + if [[ "$operation" ]]; then + # ignore error about 'sep' being unused + # shellcheck disable=SC2034 + IFS=':=' read -r body_key sep body_value <<< "$key" + body_parameters[${body_key}]=${body_value} + fi + ;; + +([^=]):*) + # Parse header arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS=':' read -r header_name header_value <<< "$key" + header_arguments[$header_name]=$header_value + else + curl_arguments+=" $key" + fi + ;; + -) + body_content_temp_file=$(mktemp) + cat - > "$body_content_temp_file" + ;; + *=*) + # Parse operation arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS='=' read -r parameter_name parameter_value <<< "$key" + if [[ -z "${operation_parameters[$parameter_name]+foo}" ]]; then + operation_parameters[$parameter_name]=$(url_escape "${parameter_value}") + else + operation_parameters[$parameter_name]+=":::"$(url_escape "${parameter_value}") + fi + else + curl_arguments+=" $key" + fi + ;; + *) + # If we are before the operation, treat the arguments as cURL arguments + if [[ "x$operation" == "x" ]]; then + # Maintain quotes around cURL arguments if necessary + space_regexp="[[:space:]]" + if [[ $key =~ $space_regexp ]]; then + curl_arguments+=" \"$key\"" + else + curl_arguments+=" $key" + fi + fi + ;; +esac +done + + +# Check if user provided host name +if [[ -z "$host" ]]; then + ERROR_MSG="ERROR: No hostname provided!!! You have to provide on command line option '--host ...'" + exit 1 +fi + +# Check if user specified operation ID +if [[ -z "$operation" ]]; then + ERROR_MSG="ERROR: No operation specified!!!" + exit 1 +fi + + +# Run cURL command based on the operation ID +case $operation in + v1BalancesGet) + call_v1BalancesGet + ;; + v1OrdersCancelAllPost) + call_v1OrdersCancelAllPost + ;; + v1OrdersCancelPost) + call_v1OrdersCancelPost + ;; + v1OrdersGet) + call_v1OrdersGet + ;; + v1OrdersPost) + call_v1OrdersPost + ;; + v1OrdersStatusClientOrderIdGet) + call_v1OrdersStatusClientOrderIdGet + ;; + v1PositionsGet) + call_v1PositionsGet + ;; + *) + ERROR_MSG="ERROR: Unknown operation: $operation" + exit 1 +esac diff --git a/ems-cloud-mgmt-sdk/bash/client.sh.bash-completion b/ems-cloud-mgmt-sdk/bash/client.sh.bash-completion new file mode 100644 index 0000000000..b5852c2775 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/client.sh.bash-completion @@ -0,0 +1,254 @@ +# completion -*- shell-script -*- + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! openapi-generator (https://openapi-generator.tech) +# ! FROM OPENAPI SPECIFICATION IN JSON. +# ! +# ! +# ! +# ! System wide installation: +# ! +# ! $ sudo cp .bash-completion /etc/bash-completion.d/ +# ! +# ! +# ! User home installation (add this line to .bash_profile): +# ! +# ! [ -r ~/.bash-completion ] && source ~/.bash-completion +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +# +# Check if this is OSX, if so defined custom init_completion +# +if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion() + { + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword + } +fi + +_() +{ + local cur + local prev + local words + local cword + + # The reference of currently selected REST operation + local operation="" + + # The list of available operation in the REST service + # It's modelled as an associative array for efficient key lookup + declare -A operations + operations["v1BalancesGet"]=1 + operations["v1OrdersCancelAllPost"]=1 + operations["v1OrdersCancelPost"]=1 + operations["v1OrdersGet"]=1 + operations["v1OrdersPost"]=1 + operations["v1OrdersStatusClientOrderIdGet"]=1 + operations["v1PositionsGet"]=1 + + # An associative array of operations to their parameters + # Only include path, query and header parameters + declare -A operation_parameters + operation_parameters["v1BalancesGet"]="exchange_id= " + operation_parameters["v1OrdersCancelAllPost"]="" + operation_parameters["v1OrdersCancelPost"]="" + operation_parameters["v1OrdersGet"]="exchange_id= " + operation_parameters["v1OrdersPost"]="" + operation_parameters["v1OrdersStatusClientOrderIdGet"]="client_order_id= " + operation_parameters["v1PositionsGet"]="exchange_id= " + + # An associative array of possible values for enum parameters + declare -A operation_parameters_enum_values + + # + # Check if this is OSX and use special __osx_init_completion function + # + if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion || return + else + _init_completion -s || return + fi + + + # Check if operation is already in the command line provided + for word in "${words[@]}"; do + if [[ -n $word && ${operations[$word]} ]]; then + operation="${word}" + fi + done + + if [[ -z $operation ]]; then + case $prev in + --ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\ + --ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\ + --help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\ + --mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\ + --pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\ + --range|-X|--request|--retry|--retry-delay|--retry-max-time|\ + --socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\ + --time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\ + --write-out|--resolve|--tlsuser|--tlspassword|--about) + return + ;; + -K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\ + --key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\ + --trace-ascii|--netrc-file) + _filedir + return + ;; + --cacert|-E|--cert) + _filedir '@(c?(e)rt|cer|pem|der)' + return + ;; + --capath) + _filedir -d + return + ;; + --cert-type|--key-type) + COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) ) + return + ;; + --crlfile) + _filedir crl + return + ;; + -d|--data|--data-ascii|--data-binary|--data-urlencode) + if [[ $cur == \@* ]]; then + cur=${cur:1} + _filedir + COMPREPLY=( "${COMPREPLY[@]/#/@}" ) + fi + return + ;; + --delegation) + COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) ) + return + ;; + --engine) + COMPREPLY=( $( compgen -W 'list' -- "$cur" ) ) + return + ;; + --ftp-method) + COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) ) + return + ;; + --ftp-ssl-ccc-mode) + COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) ) + return + ;; + --interface) + _available_interfaces -a + return + ;; + -x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname) + _known_hosts_real + return + ;; + --pubkey) + _filedir pub + return + ;; + --stderr) + COMPREPLY=( $( compgen -W '-' -- "$cur" ) ) + _filedir + return + ;; + --tlsauthtype) + COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) ) + return + ;; + --host) + COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) ) + return + ;; + -ct|--content-type|-ac|--accept) + COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) ) + return + ;; + esac + fi + + # + # Complete the server address based on ~/.ssh/known_hosts + # and ~/.ssh/config + # + local prefix=${COMP_WORDS[COMP_CWORD-2]} + local colon=${COMP_WORDS[COMP_CWORD-1]} + if [[ "$colon" == ":" && ( $prefix == "https" || $prefix == "http" ) ]]; then + COMPREPLY=() + local comp_ssh_hosts=`[[ -f ~/.ssh/known_hosts ]] && \ + ( cat ~/.ssh/known_hosts | \ + grep '^[a-zA-Z0-9]' | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ) ; + [[ -f ~/.ssh/config ]] && \ + ( cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}' )` + COMPREPLY=( $( compgen -P '//' -W '${comp_ssh_hosts}' -- "${cur:2}") ) + return + fi + + # + # Complete the and cURL's arguments + # + if [[ $cur == -* ]]; then + COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) ) + return + fi + + # + # If the argument starts with a letter this could be either an operation + # or an operation parameter + # When $cur is empty, suggest the list of operations by default + # + if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then + # If operation has not been yet selected, suggest the list of operations + # otherwise suggest arguments of this operation as declared in the + # OpenAPI specification + if [[ -z $operation ]]; then + COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) + else + COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + compopt -o nospace + fi + return + fi + +} && +complete -F _ + +# ex: ts=4 sw=4 et filetype=sh diff --git a/ems-cloud-mgmt-sdk/bash/docs/Balance.md b/ems-cloud-mgmt-sdk/bash/docs/Balance.md new file mode 100644 index 0000000000..bc01a4dee1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/Balance.md @@ -0,0 +1,11 @@ +# Balance + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [optional] [default to null] +**data** | [**array[BalanceData]**](BalanceData.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/BalanceData.md b/ems-cloud-mgmt-sdk/bash/docs/BalanceData.md new file mode 100644 index 0000000000..83d1ff0c16 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/BalanceData.md @@ -0,0 +1,17 @@ +# Balance_data + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**assetUnderscoreidUnderscoreexchange** | **string** | | [optional] [default to null] +**assetUnderscoreidUnderscorecoinapi** | **string** | | [optional] [default to null] +**balance** | **float** | | [optional] [default to null] +**available** | **float** | | [optional] [default to null] +**locked** | **float** | | [optional] [default to null] +**lastUnderscoreupdatedUnderscoreby** | **string** | | [optional] [default to null] +**rateUnderscoreusd** | **float** | | [optional] [default to null] +**traded** | **float** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/BalancesApi.md b/ems-cloud-mgmt-sdk/bash/docs/BalancesApi.md new file mode 100644 index 0000000000..47c2662953 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/BalancesApi.md @@ -0,0 +1,44 @@ +# BalancesApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1BalancesGet**](BalancesApi.md#v1BalancesGet) | **GET** /v1/balances | Get balances + + + +## v1BalancesGet + +Get balances + +Get current currency balance from all or single exchange. + +### Example + +```bash + v1BalancesGet exchange_id=value +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **string** | Filter the balances to the specific exchange. | [optional] [default to null] + +### Return type + +[**array[Balance]**](Balance.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not Applicable +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/bash/docs/Fills.md b/ems-cloud-mgmt-sdk/bash/docs/Fills.md new file mode 100644 index 0000000000..7c64a109c2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/Fills.md @@ -0,0 +1,12 @@ +# Fills + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_time** | **string** | | [optional] [default to null] +**price** | **integer** | | [optional] [default to null] +**amount** | **integer** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/MessageReject.md b/ems-cloud-mgmt-sdk/bash/docs/MessageReject.md new file mode 100644 index 0000000000..fc46c1c103 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/MessageReject.md @@ -0,0 +1,14 @@ +# MessageReject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **string** | | [optional] [default to null] +**rejectUnderscorereason** | [**RejectReason**](RejectReason.md) | | [optional] [default to null] +**exchangeUnderscoreid** | **string** | | [optional] [default to null] +**message** | **string** | | [optional] [default to null] +**rejectedUnderscoremessage** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrdSide.md b/ems-cloud-mgmt-sdk/bash/docs/OrdSide.md new file mode 100644 index 0000000000..c4ae382f58 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrdSide.md @@ -0,0 +1,9 @@ +# OrdSide + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrdStatus.md b/ems-cloud-mgmt-sdk/bash/docs/OrdStatus.md new file mode 100644 index 0000000000..7db73e974a --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrdStatus.md @@ -0,0 +1,9 @@ +# OrdStatus + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrdType.md b/ems-cloud-mgmt-sdk/bash/docs/OrdType.md new file mode 100644 index 0000000000..ac8ce76edd --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrdType.md @@ -0,0 +1,9 @@ +# OrdType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrderCancelAllRequest.md b/ems-cloud-mgmt-sdk/bash/docs/OrderCancelAllRequest.md new file mode 100644 index 0000000000..cab7b5dd52 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrderCancelAllRequest.md @@ -0,0 +1,10 @@ +# OrderCancelAllRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrderCancelSingleRequest.md b/ems-cloud-mgmt-sdk/bash/docs/OrderCancelSingleRequest.md new file mode 100644 index 0000000000..87997e6e71 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrderCancelSingleRequest.md @@ -0,0 +1,12 @@ +# OrderCancelSingleRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [default to null] +**exchangeUnderscoreorderUnderscoreid** | **string** | | [optional] [default to null] +**clientUnderscoreorderUnderscoreid** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReport.md b/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReport.md new file mode 100644 index 0000000000..0de7097d84 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReport.md @@ -0,0 +1,29 @@ +# OrderExecutionReport + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [default to null] +**clientUnderscoreorderUnderscoreid** | **string** | | [default to null] +**symbolUnderscoreidUnderscoreexchange** | **string** | | [optional] [default to null] +**symbolUnderscoreidUnderscorecoinapi** | **string** | | [optional] [default to null] +**amountUnderscoreorder** | **integer** | | [default to null] +**price** | **integer** | | [default to null] +**side** | [**OrdSide**](OrdSide.md) | | [default to null] +**orderUnderscoretype** | [**OrdType**](OrdType.md) | | [default to null] +**timeUnderscoreinUnderscoreforce** | [**TimeInForce**](TimeInForce.md) | | [default to null] +**expireUnderscoretime** | **string** | | [optional] [default to null] +**execUnderscoreinst** | **array[string]** | | [optional] [default to null] +**clientUnderscoreorderUnderscoreidUnderscoreformatUnderscoreexchange** | **string** | | [default to null] +**exchangeUnderscoreorderUnderscoreid** | **string** | | [optional] [default to null] +**amountUnderscoreopen** | **integer** | | [default to null] +**amountUnderscorefilled** | **integer** | | [default to null] +**avgUnderscorepx** | **integer** | | [optional] [default to null] +**status** | [**OrdStatus**](OrdStatus.md) | | [default to null] +**statusUnderscorehistory** | **array[array[string]]** | | [optional] [default to null] +**errorUnderscoremessage** | **string** | | [optional] [default to null] +**fills** | [**array[Fills]**](Fills.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReportAllOf.md b/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReportAllOf.md new file mode 100644 index 0000000000..9f4417ca67 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrderExecutionReportAllOf.md @@ -0,0 +1,18 @@ +# OrderExecutionReport_allOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**clientUnderscoreorderUnderscoreidUnderscoreformatUnderscoreexchange** | **string** | | [default to null] +**exchangeUnderscoreorderUnderscoreid** | **string** | | [optional] [default to null] +**amountUnderscoreopen** | **integer** | | [default to null] +**amountUnderscorefilled** | **integer** | | [default to null] +**avgUnderscorepx** | **integer** | | [optional] [default to null] +**status** | [**OrdStatus**](OrdStatus.md) | | [default to null] +**statusUnderscorehistory** | **array[array[string]]** | | [optional] [default to null] +**errorUnderscoremessage** | **string** | | [optional] [default to null] +**fills** | [**array[Fills]**](Fills.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrderNewSingleRequest.md b/ems-cloud-mgmt-sdk/bash/docs/OrderNewSingleRequest.md new file mode 100644 index 0000000000..97a016c138 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrderNewSingleRequest.md @@ -0,0 +1,20 @@ +# OrderNewSingleRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [default to null] +**clientUnderscoreorderUnderscoreid** | **string** | | [default to null] +**symbolUnderscoreidUnderscoreexchange** | **string** | | [optional] [default to null] +**symbolUnderscoreidUnderscorecoinapi** | **string** | | [optional] [default to null] +**amountUnderscoreorder** | **integer** | | [default to null] +**price** | **integer** | | [default to null] +**side** | [**OrdSide**](OrdSide.md) | | [default to null] +**orderUnderscoretype** | [**OrdType**](OrdType.md) | | [default to null] +**timeUnderscoreinUnderscoreforce** | [**TimeInForce**](TimeInForce.md) | | [default to null] +**expireUnderscoretime** | **string** | | [optional] [default to null] +**execUnderscoreinst** | **array[string]** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/OrdersApi.md b/ems-cloud-mgmt-sdk/bash/docs/OrdersApi.md new file mode 100644 index 0000000000..8f868e442a --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/OrdersApi.md @@ -0,0 +1,188 @@ +# OrdersApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1OrdersCancelAllPost**](OrdersApi.md#v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +[**v1OrdersCancelPost**](OrdersApi.md#v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +[**v1OrdersGet**](OrdersApi.md#v1OrdersGet) | **GET** /v1/orders | Get open orders +[**v1OrdersPost**](OrdersApi.md#v1OrdersPost) | **POST** /v1/orders | Send new order +[**v1OrdersStatusClientOrderIdGet**](OrdersApi.md#v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report + + + +## v1OrdersCancelAllPost + +Cancel all orders request + +This request cancels all open orders on single specified exchange. + +### Example + +```bash + v1OrdersCancelAllPost +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderCancelAllRequest** | [**OrderCancelAllRequest**](OrderCancelAllRequest.md) | OrderCancelAllRequest object. | + +### Return type + +[**MessageReject**](MessageReject.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## v1OrdersCancelPost + +Cancel order request + +Request cancel for an existing order. The order can be canceled using the 'client_order_id' or 'exchange_order_id'. + +### Example + +```bash + v1OrdersCancelPost +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderCancelSingleRequest** | [**OrderCancelSingleRequest**](OrderCancelSingleRequest.md) | OrderCancelSingleRequest object. | + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## v1OrdersGet + +Get open orders + +Get last execution reports for open orders across all or single exchange. + +### Example + +```bash + v1OrdersGet exchange_id=value +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **string** | Filter the open orders to the specific exchange. | [optional] [default to null] + +### Return type + +[**array[OrderExecutionReport]**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not Applicable +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## v1OrdersPost + +Send new order + +This request creating new order for the specific exchange. + +### Example + +```bash + v1OrdersPost +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderNewSingleRequest** | [**OrderNewSingleRequest**](OrderNewSingleRequest.md) | OrderNewSingleRequest object. | + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## v1OrdersStatusClientOrderIdGet + +Get order execution report + +Get the last order execution report for the specified order. The requested order does not need to be active or opened. + +### Example + +```bash + v1OrdersStatusClientOrderIdGet client_order_id=value +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **clientOrderId** | **string** | The unique identifier of the order assigned by the client. | [default to null] + +### Return type + +[**OrderExecutionReport**](OrderExecutionReport.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not Applicable +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/bash/docs/Position.md b/ems-cloud-mgmt-sdk/bash/docs/Position.md new file mode 100644 index 0000000000..3ddf4da19c --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/Position.md @@ -0,0 +1,11 @@ +# Position + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchangeUnderscoreid** | **string** | | [optional] [default to null] +**data** | [**array[PositionData]**](PositionData.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/PositionData.md b/ems-cloud-mgmt-sdk/bash/docs/PositionData.md new file mode 100644 index 0000000000..4468dfe156 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/PositionData.md @@ -0,0 +1,19 @@ +# Position_data + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbolUnderscoreidUnderscoreexchange** | **string** | | [optional] [default to null] +**symbolUnderscoreidUnderscorecoinapi** | **string** | | [optional] [default to null] +**avgUnderscoreentryUnderscoreprice** | **integer** | | [optional] [default to null] +**quantity** | **integer** | | [optional] [default to null] +**side** | [**OrdSide**](OrdSide.md) | | [optional] [default to null] +**unrealizedUnderscorepnl** | **integer** | | [optional] [default to null] +**leverage** | **integer** | | [optional] [default to null] +**crossUnderscoremargin** | **boolean** | | [optional] [default to null] +**liquidationUnderscoreprice** | **integer** | | [optional] [default to null] +**rawUnderscoredata** | **map** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/PositionsApi.md b/ems-cloud-mgmt-sdk/bash/docs/PositionsApi.md new file mode 100644 index 0000000000..db401ff771 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/PositionsApi.md @@ -0,0 +1,44 @@ +# PositionsApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**v1PositionsGet**](PositionsApi.md#v1PositionsGet) | **GET** /v1/positions | Get open positions + + + +## v1PositionsGet + +Get open positions + +Get current open positions across all or single exchange. + +### Example + +```bash + v1PositionsGet exchange_id=value +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **exchangeId** | **string** | Filter the balances to the specific exchange. | [optional] [default to null] + +### Return type + +[**array[Position]**](Position.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not Applicable +- **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/bash/docs/RejectReason.md b/ems-cloud-mgmt-sdk/bash/docs/RejectReason.md new file mode 100644 index 0000000000..62911d138e --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/RejectReason.md @@ -0,0 +1,9 @@ +# RejectReason + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/TimeInForce.md b/ems-cloud-mgmt-sdk/bash/docs/TimeInForce.md new file mode 100644 index 0000000000..97376e0f8d --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/TimeInForce.md @@ -0,0 +1,9 @@ +# TimeInForce + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/bash/docs/ValidationError.md b/ems-cloud-mgmt-sdk/bash/docs/ValidationError.md new file mode 100644 index 0000000000..3c78e941e4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/bash/docs/ValidationError.md @@ -0,0 +1,14 @@ +# ValidationError + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **string** | | [optional] [default to null] +**title** | **string** | | [optional] [default to null] +**status** | **integer** | | [optional] [default to null] +**traceId** | **string** | | [optional] [default to null] +**errors** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/c/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/c/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/c/.openapi-generator/FILES new file mode 100644 index 0000000000..43bac05c6a --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/.openapi-generator/FILES @@ -0,0 +1,96 @@ +.openapi-generator-ignore +CMakeLists.txt +Packing.cmake +README.md +api/BalancesAPI.c +api/BalancesAPI.h +api/OrdersAPI.c +api/OrdersAPI.h +api/PositionsAPI.c +api/PositionsAPI.h +docs/BalancesAPI.md +docs/OrdersAPI.md +docs/PositionsAPI.md +docs/balance.md +docs/balance_data.md +docs/fills.md +docs/message_reject.md +docs/ord_side.md +docs/ord_status.md +docs/ord_type.md +docs/order_cancel_all_request.md +docs/order_cancel_single_request.md +docs/order_execution_report.md +docs/order_execution_report_all_of.md +docs/order_new_single_request.md +docs/position.md +docs/position_data.md +docs/reject_reason.md +docs/time_in_force.md +docs/validation_error.md +external/cJSON.c +external/cJSON.h +external/cJSON.licence +include/apiClient.h +include/binary.h +include/keyValuePair.h +include/list.h +libcurl.licence +model/balance.c +model/balance.h +model/balance_data.c +model/balance_data.h +model/fills.c +model/fills.h +model/message_reject.c +model/message_reject.h +model/object.c +model/object.h +model/ord_side.c +model/ord_side.h +model/ord_status.c +model/ord_status.h +model/ord_type.c +model/ord_type.h +model/order_cancel_all_request.c +model/order_cancel_all_request.h +model/order_cancel_single_request.c +model/order_cancel_single_request.h +model/order_execution_report.c +model/order_execution_report.h +model/order_execution_report_all_of.c +model/order_execution_report_all_of.h +model/order_new_single_request.c +model/order_new_single_request.h +model/position.c +model/position.h +model/position_data.c +model/position_data.h +model/reject_reason.c +model/reject_reason.h +model/time_in_force.c +model/time_in_force.h +model/validation_error.c +model/validation_error.h +src/apiClient.c +src/apiKey.c +src/binary.c +src/list.c +uncrustify-rules.cfg +unit-test/test_balance.c +unit-test/test_balance_data.c +unit-test/test_fills.c +unit-test/test_message_reject.c +unit-test/test_ord_side.c +unit-test/test_ord_status.c +unit-test/test_ord_type.c +unit-test/test_order_cancel_all_request.c +unit-test/test_order_cancel_single_request.c +unit-test/test_order_execution_report.c +unit-test/test_order_execution_report_all_of.c +unit-test/test_order_new_single_request.c +unit-test/test_position.c +unit-test/test_position_data.c +unit-test/test_reject_reason.c +unit-test/test_time_in_force.c +unit-test/test_validation_error.c diff --git a/ems-cloud-mgmt-sdk/c/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/c/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/c/CMakeLists.txt b/ems-cloud-mgmt-sdk/c/CMakeLists.txt new file mode 100644 index 0000000000..3ad93e2d93 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/CMakeLists.txt @@ -0,0 +1,202 @@ +cmake_minimum_required (VERSION 2.6...3.10.2) +project (CGenerator) + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_C_VISIBILITY_PRESET default) +set(CMAKE_CXX_VISIBILITY_PRESET default) +set(CMAKE_VISIBILITY_INLINES_HIDDEN OFF) +set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) + +option(BUILD_SHARED_LIBS "Build using shared libraries" ON) + +find_package(OpenSSL) + +if (OPENSSL_FOUND) + message (STATUS "OPENSSL found") + + set(CMAKE_C_FLAGS "-DOPENSSL") + if(CMAKE_VERSION VERSION_LESS 3.4) + include_directories(${OPENSSL_INCLUDE_DIR}) + include_directories(${OPENSSL_INCLUDE_DIRS}) + link_directories(${OPENSSL_LIBRARIES}) + endif() + + message(STATUS "Using OpenSSL ${OPENSSL_VERSION}") +else() + message (STATUS "OpenSSL Not found.") +endif() + +set(pkgName "ems___rest_api") + +# this default version can be overridden in PreTarget.cmake +set(PROJECT_VERSION_MAJOR 0) +set(PROJECT_VERSION_MINOR 0) +set(PROJECT_VERSION_PATCH 1) + +find_package(CURL 7.58.0 REQUIRED) +if(CURL_FOUND) + include_directories(${CURL_INCLUDE_DIR}) + set(PLATFORM_LIBRARIES ${PLATFORM_LIBRARIES} ${CURL_LIBRARIES} ) +else(CURL_FOUND) + message(FATAL_ERROR "Could not find the CURL library and development files.") +endif() + +set(SRCS + src/list.c + src/apiKey.c + src/apiClient.c + src/binary.c + external/cJSON.c + model/object.c + model/balance.c + model/balance_data.c + model/fills.c + model/message_reject.c + model/ord_side.c + model/ord_status.c + model/ord_type.c + model/order_cancel_all_request.c + model/order_cancel_single_request.c + model/order_execution_report.c + model/order_execution_report_all_of.c + model/order_new_single_request.c + model/position.c + model/position_data.c + model/reject_reason.c + model/time_in_force.c + model/validation_error.c + api/BalancesAPI.c + api/OrdersAPI.c + api/PositionsAPI.c + +) + +set(HDRS + include/apiClient.h + include/list.h + include/binary.h + include/keyValuePair.h + external/cJSON.h + model/object.h + model/balance.h + model/balance_data.h + model/fills.h + model/message_reject.h + model/ord_side.h + model/ord_status.h + model/ord_type.h + model/order_cancel_all_request.h + model/order_cancel_single_request.h + model/order_execution_report.h + model/order_execution_report_all_of.h + model/order_new_single_request.h + model/position.h + model/position_data.h + model/reject_reason.h + model/time_in_force.h + model/validation_error.h + api/BalancesAPI.h + api/OrdersAPI.h + api/PositionsAPI.h + +) + +include(PreTarget.cmake OPTIONAL) + +set(PROJECT_VERSION_STRING "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") + +# Add library with project file with project name as library name +add_library(${pkgName} ${SRCS} ${HDRS}) +# Link dependent libraries +if(NOT CMAKE_VERSION VERSION_LESS 3.4) + target_link_libraries(${pkgName} PRIVATE OpenSSL::SSL OpenSSL::Crypto) +endif() +target_link_libraries(${pkgName} PUBLIC ${CURL_LIBRARIES} ) +target_include_directories( + ${pkgName} PUBLIC $ + $ +) + +include(PostTarget.cmake OPTIONAL) + +# installation of libraries, headers, and config files +if (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in) + install(TARGETS ${pkgName} DESTINATION lib) +else() + include(GNUInstallDirs) + install(TARGETS ${pkgName} DESTINATION lib EXPORT ${pkgName}Targets) + + foreach(HDR_FILE ${HDRS}) + get_filename_component(HDR_DIRECTORY ${HDR_FILE} DIRECTORY) + get_filename_component(ABSOLUTE_HDR_DIRECTORY ${HDR_DIRECTORY} ABSOLUTE) + file(RELATIVE_PATH RELATIVE_HDR_PATH ${CMAKE_CURRENT_SOURCE_DIR} ${ABSOLUTE_HDR_DIRECTORY}) + install(FILES ${HDR_FILE} DESTINATION include/${pkgName}/${RELATIVE_HDR_PATH}) + endforeach() + + include(CMakePackageConfigHelpers) + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}ConfigVersion.cmake" + VERSION "${PROJECT_VERSION_STRING}" + COMPATIBILITY AnyNewerVersion + ) + + export(EXPORT ${pkgName}Targets + FILE "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}Targets.cmake" + NAMESPACE ${pkgName}:: + ) + + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}Config.cmake" + @ONLY + ) + + set(ConfigPackageLocation lib/cmake/${pkgName}) + install(EXPORT ${pkgName}Targets + FILE + ${pkgName}Targets.cmake + NAMESPACE + ${pkgName}:: + DESTINATION + ${ConfigPackageLocation} + ) + install( + FILES + "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}Config.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}ConfigVersion.cmake" + DESTINATION + ${ConfigPackageLocation} + ) +endif() + +# make installation packages +include(Packing.cmake OPTIONAL) + +# Setting file variables to null +set(SRCS "") +set(HDRS "") + + +## This section shows how to use the above compiled library to compile the source files +## set source files +#set(SRCS +# unit-tests/manual-BalancesAPI.c +# unit-tests/manual-OrdersAPI.c +# unit-tests/manual-PositionsAPI.c +#) + +##set header files +#set(HDRS +#) + +## loop over all files in SRCS variable +#foreach(SOURCE_FILE ${SRCS}) +# # Get only the file name from the file as add_executable does not support executable with slash("/") +# get_filename_component(FILE_NAME_ONLY ${SOURCE_FILE} NAME_WE) +# # Remove .c from the file name and set it as executable name +# string( REPLACE ".c" "" EXECUTABLE_FILE ${FILE_NAME_ONLY}) +# # Add executable for every source file in SRCS +# add_executable(unit-${EXECUTABLE_FILE} ${SOURCE_FILE}) +# # Link above created library to executable and dependent library curl +# target_link_libraries(unit-${EXECUTABLE_FILE} ${CURL_LIBRARIES} ${pkgName} ) +#endforeach(SOURCE_FILE ${SRCS}) diff --git a/ems-cloud-mgmt-sdk/c/Packing.cmake b/ems-cloud-mgmt-sdk/c/Packing.cmake new file mode 100644 index 0000000000..15bd4c8d5e --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/Packing.cmake @@ -0,0 +1,24 @@ +set(CPACK_PACKAGE_NAME lib${pkgName}) + +set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) + +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY ${PROJECT_PACKAGE_DESCRIPTION_SUMMARY}) +set(CPACK_PACKAGE_VENDOR ${PROJECT_PACKAGE_VENDOR}) +set(CPACK_PACKAGE_CONTACT ${PROJECT_PACKAGE_CONTACT}) +set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${PROJECT_PACKAGE_MAINTAINER}) + +set(CPACK_VERBATIM_VARIABLES YES) + +set(CPACK_PACKAGE_INSTALL_DIRECTORY ${CPACK_PACKAGE_NAME}) + +set(CPACK_PACKAGING_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) + +set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) + +set(CPACK_DEB_COMPONENT_INSTALL YES) + +set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS TRUE) + +include(CPack) \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/c/README.md b/ems-cloud-mgmt-sdk/c/README.md new file mode 100644 index 0000000000..fef3729d65 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/README.md @@ -0,0 +1,105 @@ +# C API client for ems___rest_api + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: v1 +- Package version: +- Build package: org.openapitools.codegen.languages.CLibcurlClientCodegen +For more information, please visit [https://www.coinapi.io](https://www.coinapi.io) + +## Installation +You'll need the `curl 7.58.0` package in order to build the API. To have code formatted nicely, you also need to have uncrustify version 0.67 or later. + +# Prerequisites + +## Install the `curl 7.58.0` package with the following command on Linux. +```bash +sudo apt remove curl +wget http://curl.haxx.se/download/curl-7.58.0.tar.gz +tar -xvf curl-7.58.0.tar.gz +cd curl-7.58.0/ +./configure +make +sudo make install +``` +## Install the `uncrustify 0.67` package with the following command on Linux. +```bash +git clone https://github.com/uncrustify/uncrustify.git +cd uncrustify +mkdir build +cd build +cmake .. +make +sudo make install +``` + +## Compile the sample: +This will compile the generated code and create a library in the build folder which has to be linked to the codes where API will be used. +```bash +mkdir build +cd build +// To install library to specific location, use following commands +cmake -DCMAKE_INSTALL_PREFIX=/pathtolocation .. +// for normal install use following command +cmake .. +make +sudo make install +``` +## How to use compiled library +Considering the test/source code which uses the API is written in main.c(respective api include is written and all objects necessary are defined and created) + +To compile main.c(considering the file is present in build folder) use following command +-L - location of the library(not required if cmake with normal installation is performed) +-l library name +```bash +gcc main.c -L. -lems___rest_api -o main +``` +Once compiled, you can run it with ``` ./main ``` + +Note: You don't need to specify includes for models and include folder separately as they are path linked. You just have to import the api.h file in your code, the include linking will work. + +## Documentation for API Endpoints + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Category | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*BalancesAPI* | [**BalancesAPI_v1BalancesGet**](docs/BalancesAPI.md#BalancesAPI_v1BalancesGet) | **GET** /v1/balances | Get balances +*OrdersAPI* | [**OrdersAPI_v1OrdersCancelAllPost**](docs/OrdersAPI.md#OrdersAPI_v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +*OrdersAPI* | [**OrdersAPI_v1OrdersCancelPost**](docs/OrdersAPI.md#OrdersAPI_v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +*OrdersAPI* | [**OrdersAPI_v1OrdersGet**](docs/OrdersAPI.md#OrdersAPI_v1OrdersGet) | **GET** /v1/orders | Get open orders +*OrdersAPI* | [**OrdersAPI_v1OrdersPost**](docs/OrdersAPI.md#OrdersAPI_v1OrdersPost) | **POST** /v1/orders | Send new order +*OrdersAPI* | [**OrdersAPI_v1OrdersStatusClientOrderIdGet**](docs/OrdersAPI.md#OrdersAPI_v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report +*PositionsAPI* | [**PositionsAPI_v1PositionsGet**](docs/PositionsAPI.md#PositionsAPI_v1PositionsGet) | **GET** /v1/positions | Get open positions + + +## Documentation for Models + + - [balance_t](docs/balance.md) + - [balance_data_t](docs/balance_data.md) + - [fills_t](docs/fills.md) + - [message_reject_t](docs/message_reject.md) + - [ord_side_t](docs/ord_side.md) + - [ord_status_t](docs/ord_status.md) + - [ord_type_t](docs/ord_type.md) + - [order_cancel_all_request_t](docs/order_cancel_all_request.md) + - [order_cancel_single_request_t](docs/order_cancel_single_request.md) + - [order_execution_report_t](docs/order_execution_report.md) + - [order_execution_report_all_of_t](docs/order_execution_report_all_of.md) + - [order_new_single_request_t](docs/order_new_single_request.md) + - [position_t](docs/position.md) + - [position_data_t](docs/position_data.md) + - [reject_reason_t](docs/reject_reason.md) + - [time_in_force_t](docs/time_in_force.md) + - [validation_error_t](docs/validation_error.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. + +## Author + +support@coinapi.io + diff --git a/ems-cloud-mgmt-sdk/c/api/BalancesAPI.c b/ems-cloud-mgmt-sdk/c/api/BalancesAPI.c new file mode 100644 index 0000000000..2556930e5f --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/BalancesAPI.c @@ -0,0 +1,114 @@ +#include +#include +#include +#include "BalancesAPI.h" + +#define MAX_NUMBER_LENGTH 16 +#define MAX_BUFFER_LENGTH 4096 +#define intToStr(dst, src) \ + do {\ + char dst[256];\ + snprintf(dst, 256, "%ld", (long int)(src));\ +}while(0) + + +// Get balances +// +// Get current currency balance from all or single exchange. +// +list_t* +BalancesAPI_v1BalancesGet(apiClient_t *apiClient, char * exchange_id ) +{ + list_t *localVarQueryParameters = list_createList(); + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = NULL; + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/balances")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/balances"); + + + + + // query parameters + char *keyQuery_exchange_id = NULL; + char * valueQuery_exchange_id = NULL; + keyValuePair_t *keyPairQuery_exchange_id = 0; + if (exchange_id) + { + keyQuery_exchange_id = strdup("exchange_id"); + valueQuery_exchange_id = strdup((exchange_id)); + keyPairQuery_exchange_id = keyValuePair_create(keyQuery_exchange_id, valueQuery_exchange_id); + list_addElement(localVarQueryParameters,keyPairQuery_exchange_id); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "GET"); + + if (apiClient->response_code == 200) { + printf("%s\n","Collection of balances."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Exchange is unreachable."); + } + cJSON *BalancesAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + if(!cJSON_IsArray(BalancesAPIlocalVarJSON)) { + return 0;//nonprimitive container + } + list_t *elementToReturn = list_createList(); + cJSON *VarJSON; + cJSON_ArrayForEach(VarJSON, BalancesAPIlocalVarJSON) + { + if(!cJSON_IsObject(VarJSON)) + { + // return 0; + } + char *localVarJSONToChar = cJSON_Print(VarJSON); + list_addElement(elementToReturn , localVarJSONToChar); + } + + cJSON_Delete( BalancesAPIlocalVarJSON); + cJSON_Delete( VarJSON); + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + list_freeList(localVarQueryParameters); + + + list_freeList(localVarHeaderType); + + free(localVarPath); + if(keyQuery_exchange_id){ + free(keyQuery_exchange_id); + keyQuery_exchange_id = NULL; + } + if(valueQuery_exchange_id){ + free(valueQuery_exchange_id); + valueQuery_exchange_id = NULL; + } + if(keyPairQuery_exchange_id){ + keyValuePair_free(keyPairQuery_exchange_id); + keyPairQuery_exchange_id = NULL; + } + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + diff --git a/ems-cloud-mgmt-sdk/c/api/BalancesAPI.h b/ems-cloud-mgmt-sdk/c/api/BalancesAPI.h new file mode 100644 index 0000000000..eabf87848f --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/BalancesAPI.h @@ -0,0 +1,19 @@ +#include +#include +#include "../include/apiClient.h" +#include "../include/list.h" +#include "../external/cJSON.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" +#include "../model/balance.h" +#include "../model/message_reject.h" + + +// Get balances +// +// Get current currency balance from all or single exchange. +// +list_t* +BalancesAPI_v1BalancesGet(apiClient_t *apiClient, char * exchange_id ); + + diff --git a/ems-cloud-mgmt-sdk/c/api/OrdersAPI.c b/ems-cloud-mgmt-sdk/c/api/OrdersAPI.c new file mode 100644 index 0000000000..f19017b29b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/OrdersAPI.c @@ -0,0 +1,445 @@ +#include +#include +#include +#include "OrdersAPI.h" + +#define MAX_NUMBER_LENGTH 16 +#define MAX_BUFFER_LENGTH 4096 +#define intToStr(dst, src) \ + do {\ + char dst[256];\ + snprintf(dst, 256, "%ld", (long int)(src));\ +}while(0) + + +// Cancel all orders request +// +// This request cancels all open orders on single specified exchange. +// +message_reject_t* +OrdersAPI_v1OrdersCancelAllPost(apiClient_t *apiClient, order_cancel_all_request_t * order_cancel_all_request ) +{ + list_t *localVarQueryParameters = NULL; + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = list_createList(); + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/orders/cancel/all")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/orders/cancel/all"); + + + + + // Body Param + cJSON *localVarSingleItemJSON_order_cancel_all_request = NULL; + if (order_cancel_all_request != NULL) + { + //string + localVarSingleItemJSON_order_cancel_all_request = order_cancel_all_request_convertToJSON(order_cancel_all_request); + localVarBodyParameters = cJSON_Print(localVarSingleItemJSON_order_cancel_all_request); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + list_addElement(localVarContentType,"application/json"); //consumes + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "POST"); + + if (apiClient->response_code == 200) { + printf("%s\n","Result"); + } + if (apiClient->response_code == 400) { + printf("%s\n","Input model validation errors."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Exchange is unreachable."); + } + //nonprimitive not container + cJSON *OrdersAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + message_reject_t *elementToReturn = message_reject_parseFromJSON(OrdersAPIlocalVarJSON); + cJSON_Delete(OrdersAPIlocalVarJSON); + if(elementToReturn == NULL) { + // return 0; + } + + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + + + + list_freeList(localVarHeaderType); + list_freeList(localVarContentType); + free(localVarPath); + if (localVarSingleItemJSON_order_cancel_all_request) { + cJSON_Delete(localVarSingleItemJSON_order_cancel_all_request); + localVarSingleItemJSON_order_cancel_all_request = NULL; + } + free(localVarBodyParameters); + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + +// Cancel order request +// +// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. +// +order_execution_report_t* +OrdersAPI_v1OrdersCancelPost(apiClient_t *apiClient, order_cancel_single_request_t * order_cancel_single_request ) +{ + list_t *localVarQueryParameters = NULL; + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = list_createList(); + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/orders/cancel")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/orders/cancel"); + + + + + // Body Param + cJSON *localVarSingleItemJSON_order_cancel_single_request = NULL; + if (order_cancel_single_request != NULL) + { + //string + localVarSingleItemJSON_order_cancel_single_request = order_cancel_single_request_convertToJSON(order_cancel_single_request); + localVarBodyParameters = cJSON_Print(localVarSingleItemJSON_order_cancel_single_request); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + list_addElement(localVarContentType,"application/json"); //consumes + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "POST"); + + if (apiClient->response_code == 200) { + printf("%s\n","The last execution report for the order for which cancelation was requested."); + } + if (apiClient->response_code == 400) { + printf("%s\n","Input model validation errors."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Exchange is unreachable."); + } + //nonprimitive not container + cJSON *OrdersAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + order_execution_report_t *elementToReturn = order_execution_report_parseFromJSON(OrdersAPIlocalVarJSON); + cJSON_Delete(OrdersAPIlocalVarJSON); + if(elementToReturn == NULL) { + // return 0; + } + + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + + + + list_freeList(localVarHeaderType); + list_freeList(localVarContentType); + free(localVarPath); + if (localVarSingleItemJSON_order_cancel_single_request) { + cJSON_Delete(localVarSingleItemJSON_order_cancel_single_request); + localVarSingleItemJSON_order_cancel_single_request = NULL; + } + free(localVarBodyParameters); + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + +// Get open orders +// +// Get last execution reports for open orders across all or single exchange. +// +list_t* +OrdersAPI_v1OrdersGet(apiClient_t *apiClient, char * exchange_id ) +{ + list_t *localVarQueryParameters = list_createList(); + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = NULL; + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/orders")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/orders"); + + + + + // query parameters + char *keyQuery_exchange_id = NULL; + char * valueQuery_exchange_id = NULL; + keyValuePair_t *keyPairQuery_exchange_id = 0; + if (exchange_id) + { + keyQuery_exchange_id = strdup("exchange_id"); + valueQuery_exchange_id = strdup((exchange_id)); + keyPairQuery_exchange_id = keyValuePair_create(keyQuery_exchange_id, valueQuery_exchange_id); + list_addElement(localVarQueryParameters,keyPairQuery_exchange_id); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "GET"); + + if (apiClient->response_code == 200) { + printf("%s\n","Collection of order execution reports."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Filtered exchange is unreachable."); + } + cJSON *OrdersAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + if(!cJSON_IsArray(OrdersAPIlocalVarJSON)) { + return 0;//nonprimitive container + } + list_t *elementToReturn = list_createList(); + cJSON *VarJSON; + cJSON_ArrayForEach(VarJSON, OrdersAPIlocalVarJSON) + { + if(!cJSON_IsObject(VarJSON)) + { + // return 0; + } + char *localVarJSONToChar = cJSON_Print(VarJSON); + list_addElement(elementToReturn , localVarJSONToChar); + } + + cJSON_Delete( OrdersAPIlocalVarJSON); + cJSON_Delete( VarJSON); + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + list_freeList(localVarQueryParameters); + + + list_freeList(localVarHeaderType); + + free(localVarPath); + if(keyQuery_exchange_id){ + free(keyQuery_exchange_id); + keyQuery_exchange_id = NULL; + } + if(valueQuery_exchange_id){ + free(valueQuery_exchange_id); + valueQuery_exchange_id = NULL; + } + if(keyPairQuery_exchange_id){ + keyValuePair_free(keyPairQuery_exchange_id); + keyPairQuery_exchange_id = NULL; + } + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + +// Send new order +// +// This request creating new order for the specific exchange. +// +order_execution_report_t* +OrdersAPI_v1OrdersPost(apiClient_t *apiClient, order_new_single_request_t * order_new_single_request ) +{ + list_t *localVarQueryParameters = NULL; + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = list_createList(); + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/orders")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/orders"); + + + + + // Body Param + cJSON *localVarSingleItemJSON_order_new_single_request = NULL; + if (order_new_single_request != NULL) + { + //string + localVarSingleItemJSON_order_new_single_request = order_new_single_request_convertToJSON(order_new_single_request); + localVarBodyParameters = cJSON_Print(localVarSingleItemJSON_order_new_single_request); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + list_addElement(localVarContentType,"application/json"); //consumes + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "POST"); + + if (apiClient->response_code == 200) { + printf("%s\n","Created"); + } + if (apiClient->response_code == 400) { + printf("%s\n","Input model validation errors."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Exchange is unreachable."); + } + if (apiClient->response_code == 504) { + printf("%s\n","Exchange didn't responded in the defined timeout."); + } + //nonprimitive not container + cJSON *OrdersAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + order_execution_report_t *elementToReturn = order_execution_report_parseFromJSON(OrdersAPIlocalVarJSON); + cJSON_Delete(OrdersAPIlocalVarJSON); + if(elementToReturn == NULL) { + // return 0; + } + + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + + + + list_freeList(localVarHeaderType); + list_freeList(localVarContentType); + free(localVarPath); + if (localVarSingleItemJSON_order_new_single_request) { + cJSON_Delete(localVarSingleItemJSON_order_new_single_request); + localVarSingleItemJSON_order_new_single_request = NULL; + } + free(localVarBodyParameters); + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + +// Get order execution report +// +// Get the last order execution report for the specified order. The requested order does not need to be active or opened. +// +order_execution_report_t* +OrdersAPI_v1OrdersStatusClientOrderIdGet(apiClient_t *apiClient, char * client_order_id ) +{ + list_t *localVarQueryParameters = NULL; + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = NULL; + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/orders/status/{client_order_id}")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/orders/status/{client_order_id}"); + + + // Path Params + long sizeOfPathParams_client_order_id = strlen(client_order_id)+3 + strlen("{ client_order_id }"); + if(client_order_id == NULL) { + goto end; + } + char* localVarToReplace_client_order_id = malloc(sizeOfPathParams_client_order_id); + sprintf(localVarToReplace_client_order_id, "{%s}", "client_order_id"); + + localVarPath = strReplace(localVarPath, localVarToReplace_client_order_id, client_order_id); + + + list_addElement(localVarHeaderType,"application/json"); //produces + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "GET"); + + if (apiClient->response_code == 200) { + printf("%s\n","The last execution report of the requested order."); + } + if (apiClient->response_code == 404) { + printf("%s\n","The requested order was not found."); + } + //nonprimitive not container + cJSON *OrdersAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + order_execution_report_t *elementToReturn = order_execution_report_parseFromJSON(OrdersAPIlocalVarJSON); + cJSON_Delete(OrdersAPIlocalVarJSON); + if(elementToReturn == NULL) { + // return 0; + } + + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + + + + list_freeList(localVarHeaderType); + + free(localVarPath); + free(localVarToReplace_client_order_id); + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + diff --git a/ems-cloud-mgmt-sdk/c/api/OrdersAPI.h b/ems-cloud-mgmt-sdk/c/api/OrdersAPI.h new file mode 100644 index 0000000000..2631b41cdc --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/OrdersAPI.h @@ -0,0 +1,55 @@ +#include +#include +#include "../include/apiClient.h" +#include "../include/list.h" +#include "../external/cJSON.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" +#include "../model/message_reject.h" +#include "../model/order_cancel_all_request.h" +#include "../model/order_cancel_single_request.h" +#include "../model/order_execution_report.h" +#include "../model/order_new_single_request.h" +#include "../model/validation_error.h" + + +// Cancel all orders request +// +// This request cancels all open orders on single specified exchange. +// +message_reject_t* +OrdersAPI_v1OrdersCancelAllPost(apiClient_t *apiClient, order_cancel_all_request_t * order_cancel_all_request ); + + +// Cancel order request +// +// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. +// +order_execution_report_t* +OrdersAPI_v1OrdersCancelPost(apiClient_t *apiClient, order_cancel_single_request_t * order_cancel_single_request ); + + +// Get open orders +// +// Get last execution reports for open orders across all or single exchange. +// +list_t* +OrdersAPI_v1OrdersGet(apiClient_t *apiClient, char * exchange_id ); + + +// Send new order +// +// This request creating new order for the specific exchange. +// +order_execution_report_t* +OrdersAPI_v1OrdersPost(apiClient_t *apiClient, order_new_single_request_t * order_new_single_request ); + + +// Get order execution report +// +// Get the last order execution report for the specified order. The requested order does not need to be active or opened. +// +order_execution_report_t* +OrdersAPI_v1OrdersStatusClientOrderIdGet(apiClient_t *apiClient, char * client_order_id ); + + diff --git a/ems-cloud-mgmt-sdk/c/api/PositionsAPI.c b/ems-cloud-mgmt-sdk/c/api/PositionsAPI.c new file mode 100644 index 0000000000..99dc3c5812 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/PositionsAPI.c @@ -0,0 +1,114 @@ +#include +#include +#include +#include "PositionsAPI.h" + +#define MAX_NUMBER_LENGTH 16 +#define MAX_BUFFER_LENGTH 4096 +#define intToStr(dst, src) \ + do {\ + char dst[256];\ + snprintf(dst, 256, "%ld", (long int)(src));\ +}while(0) + + +// Get open positions +// +// Get current open positions across all or single exchange. +// +list_t* +PositionsAPI_v1PositionsGet(apiClient_t *apiClient, char * exchange_id ) +{ + list_t *localVarQueryParameters = list_createList(); + list_t *localVarHeaderParameters = NULL; + list_t *localVarFormParameters = NULL; + list_t *localVarHeaderType = list_createList(); + list_t *localVarContentType = NULL; + char *localVarBodyParameters = NULL; + + // create the path + long sizeOfPath = strlen("/v1/positions")+1; + char *localVarPath = malloc(sizeOfPath); + snprintf(localVarPath, sizeOfPath, "/v1/positions"); + + + + + // query parameters + char *keyQuery_exchange_id = NULL; + char * valueQuery_exchange_id = NULL; + keyValuePair_t *keyPairQuery_exchange_id = 0; + if (exchange_id) + { + keyQuery_exchange_id = strdup("exchange_id"); + valueQuery_exchange_id = strdup((exchange_id)); + keyPairQuery_exchange_id = keyValuePair_create(keyQuery_exchange_id, valueQuery_exchange_id); + list_addElement(localVarQueryParameters,keyPairQuery_exchange_id); + } + list_addElement(localVarHeaderType,"application/json"); //produces + list_addElement(localVarHeaderType,"appliction/json"); //produces + apiClient_invoke(apiClient, + localVarPath, + localVarQueryParameters, + localVarHeaderParameters, + localVarFormParameters, + localVarHeaderType, + localVarContentType, + localVarBodyParameters, + "GET"); + + if (apiClient->response_code == 200) { + printf("%s\n","Collection of positons."); + } + if (apiClient->response_code == 490) { + printf("%s\n","Exchange is unreachable."); + } + cJSON *PositionsAPIlocalVarJSON = cJSON_Parse(apiClient->dataReceived); + if(!cJSON_IsArray(PositionsAPIlocalVarJSON)) { + return 0;//nonprimitive container + } + list_t *elementToReturn = list_createList(); + cJSON *VarJSON; + cJSON_ArrayForEach(VarJSON, PositionsAPIlocalVarJSON) + { + if(!cJSON_IsObject(VarJSON)) + { + // return 0; + } + char *localVarJSONToChar = cJSON_Print(VarJSON); + list_addElement(elementToReturn , localVarJSONToChar); + } + + cJSON_Delete( PositionsAPIlocalVarJSON); + cJSON_Delete( VarJSON); + //return type + if (apiClient->dataReceived) { + free(apiClient->dataReceived); + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + } + list_freeList(localVarQueryParameters); + + + list_freeList(localVarHeaderType); + + free(localVarPath); + if(keyQuery_exchange_id){ + free(keyQuery_exchange_id); + keyQuery_exchange_id = NULL; + } + if(valueQuery_exchange_id){ + free(valueQuery_exchange_id); + valueQuery_exchange_id = NULL; + } + if(keyPairQuery_exchange_id){ + keyValuePair_free(keyPairQuery_exchange_id); + keyPairQuery_exchange_id = NULL; + } + return elementToReturn; +end: + free(localVarPath); + return NULL; + +} + diff --git a/ems-cloud-mgmt-sdk/c/api/PositionsAPI.h b/ems-cloud-mgmt-sdk/c/api/PositionsAPI.h new file mode 100644 index 0000000000..cd6cbf0162 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/api/PositionsAPI.h @@ -0,0 +1,19 @@ +#include +#include +#include "../include/apiClient.h" +#include "../include/list.h" +#include "../external/cJSON.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" +#include "../model/message_reject.h" +#include "../model/position.h" + + +// Get open positions +// +// Get current open positions across all or single exchange. +// +list_t* +PositionsAPI_v1PositionsGet(apiClient_t *apiClient, char * exchange_id ); + + diff --git a/ems-cloud-mgmt-sdk/c/docs/BalancesAPI.md b/ems-cloud-mgmt-sdk/c/docs/BalancesAPI.md new file mode 100644 index 0000000000..b0e17ad26b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/BalancesAPI.md @@ -0,0 +1,40 @@ +# BalancesAPI + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**BalancesAPI_v1BalancesGet**](BalancesAPI.md#BalancesAPI_v1BalancesGet) | **GET** /v1/balances | Get balances + + +# **BalancesAPI_v1BalancesGet** +```c +// Get balances +// +// Get current currency balance from all or single exchange. +// +list_t* BalancesAPI_v1BalancesGet(apiClient_t *apiClient, char * exchange_id); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**exchange_id** | **char \*** | Filter the balances to the specific exchange. | [optional] + +### Return type + +[list_t](balance.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/c/docs/OrdersAPI.md b/ems-cloud-mgmt-sdk/c/docs/OrdersAPI.md new file mode 100644 index 0000000000..65a5d3a1cd --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/OrdersAPI.md @@ -0,0 +1,168 @@ +# OrdersAPI + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**OrdersAPI_v1OrdersCancelAllPost**](OrdersAPI.md#OrdersAPI_v1OrdersCancelAllPost) | **POST** /v1/orders/cancel/all | Cancel all orders request +[**OrdersAPI_v1OrdersCancelPost**](OrdersAPI.md#OrdersAPI_v1OrdersCancelPost) | **POST** /v1/orders/cancel | Cancel order request +[**OrdersAPI_v1OrdersGet**](OrdersAPI.md#OrdersAPI_v1OrdersGet) | **GET** /v1/orders | Get open orders +[**OrdersAPI_v1OrdersPost**](OrdersAPI.md#OrdersAPI_v1OrdersPost) | **POST** /v1/orders | Send new order +[**OrdersAPI_v1OrdersStatusClientOrderIdGet**](OrdersAPI.md#OrdersAPI_v1OrdersStatusClientOrderIdGet) | **GET** /v1/orders/status/{client_order_id} | Get order execution report + + +# **OrdersAPI_v1OrdersCancelAllPost** +```c +// Cancel all orders request +// +// This request cancels all open orders on single specified exchange. +// +message_reject_t* OrdersAPI_v1OrdersCancelAllPost(apiClient_t *apiClient, order_cancel_all_request_t * order_cancel_all_request); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**order_cancel_all_request** | **[order_cancel_all_request_t](order_cancel_all_request.md) \*** | OrderCancelAllRequest object. | + +### Return type + +[message_reject_t](message_reject.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **OrdersAPI_v1OrdersCancelPost** +```c +// Cancel order request +// +// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. +// +order_execution_report_t* OrdersAPI_v1OrdersCancelPost(apiClient_t *apiClient, order_cancel_single_request_t * order_cancel_single_request); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**order_cancel_single_request** | **[order_cancel_single_request_t](order_cancel_single_request.md) \*** | OrderCancelSingleRequest object. | + +### Return type + +[order_execution_report_t](order_execution_report.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **OrdersAPI_v1OrdersGet** +```c +// Get open orders +// +// Get last execution reports for open orders across all or single exchange. +// +list_t* OrdersAPI_v1OrdersGet(apiClient_t *apiClient, char * exchange_id); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**exchange_id** | **char \*** | Filter the open orders to the specific exchange. | [optional] + +### Return type + +[list_t](order_execution_report.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **OrdersAPI_v1OrdersPost** +```c +// Send new order +// +// This request creating new order for the specific exchange. +// +order_execution_report_t* OrdersAPI_v1OrdersPost(apiClient_t *apiClient, order_new_single_request_t * order_new_single_request); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**order_new_single_request** | **[order_new_single_request_t](order_new_single_request.md) \*** | OrderNewSingleRequest object. | + +### Return type + +[order_execution_report_t](order_execution_report.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **OrdersAPI_v1OrdersStatusClientOrderIdGet** +```c +// Get order execution report +// +// Get the last order execution report for the specified order. The requested order does not need to be active or opened. +// +order_execution_report_t* OrdersAPI_v1OrdersStatusClientOrderIdGet(apiClient_t *apiClient, char * client_order_id); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**client_order_id** | **char \*** | The unique identifier of the order assigned by the client. | + +### Return type + +[order_execution_report_t](order_execution_report.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/c/docs/PositionsAPI.md b/ems-cloud-mgmt-sdk/c/docs/PositionsAPI.md new file mode 100644 index 0000000000..0a2f0cd882 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/PositionsAPI.md @@ -0,0 +1,40 @@ +# PositionsAPI + +All URIs are relative to *https://ems-gateway-aws-eu-central-1-dev.coinapi.io* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**PositionsAPI_v1PositionsGet**](PositionsAPI.md#PositionsAPI_v1PositionsGet) | **GET** /v1/positions | Get open positions + + +# **PositionsAPI_v1PositionsGet** +```c +// Get open positions +// +// Get current open positions across all or single exchange. +// +list_t* PositionsAPI_v1PositionsGet(apiClient_t *apiClient, char * exchange_id); +``` + +### Parameters +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +**apiClient** | **apiClient_t \*** | context containing the client configuration | +**exchange_id** | **char \*** | Filter the balances to the specific exchange. | [optional] + +### Return type + +[list_t](position.md) * + + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, appliction/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/ems-cloud-mgmt-sdk/c/docs/balance.md b/ems-cloud-mgmt-sdk/c/docs/balance.md new file mode 100644 index 0000000000..ab3923ba0e --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/balance.md @@ -0,0 +1,11 @@ +# balance_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Exchange identifier used to identify the routing destination. | [optional] +**data** | [**list_t**](balance_data.md) \* | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/balance_data.md b/ems-cloud-mgmt-sdk/c/docs/balance_data.md new file mode 100644 index 0000000000..c2fde33fb4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/balance_data.md @@ -0,0 +1,17 @@ +# balance_data_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**asset_id_exchange** | **char \*** | Exchange currency code. | [optional] +**asset_id_coinapi** | **char \*** | CoinAPI currency code. | [optional] +**balance** | **double** | Value of the current total currency balance on the exchange. | [optional] +**available** | **double** | Value of the current available currency balance on the exchange that can be used as collateral. | [optional] +**locked** | **double** | Value of the current locked currency balance by the exchange. | [optional] +**last_updated_by** | **ems___rest_api_balance_data_LASTUPDATEDBY_e** | Source of the last modification. | [optional] +**rate_usd** | **double** | Current exchange rate to the USD for the single unit of the currency. | [optional] +**traded** | **double** | Value of the current total traded. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/fills.md b/ems-cloud-mgmt-sdk/c/docs/fills.md new file mode 100644 index 0000000000..8424b5d20c --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/fills.md @@ -0,0 +1,12 @@ +# fills_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**time** | | Execution time. | [optional] +**price** | **double** | Execution price. | [optional] +**amount** | **double** | Executed quantity. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/message_reject.md b/ems-cloud-mgmt-sdk/c/docs/message_reject.md new file mode 100644 index 0000000000..6f4e52c3e2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/message_reject.md @@ -0,0 +1,14 @@ +# message_reject_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **char \*** | Message type, constant. | [optional] +**reject_reason** | **reject_reason_t \*** | | [optional] +**exchange_id** | **char \*** | If the message related to exchange, then the identifier of the exchange will be provided. | [optional] +**message** | **char \*** | Message text. | [optional] +**rejected_message** | **char \*** | Value of rejected request, if available. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/ord_side.md b/ems-cloud-mgmt-sdk/c/docs/ord_side.md new file mode 100644 index 0000000000..8faad17c31 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/ord_side.md @@ -0,0 +1,9 @@ +# ord_side_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/ord_status.md b/ems-cloud-mgmt-sdk/c/docs/ord_status.md new file mode 100644 index 0000000000..e782ceba9d --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/ord_status.md @@ -0,0 +1,9 @@ +# ord_status_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/ord_type.md b/ems-cloud-mgmt-sdk/c/docs/ord_type.md new file mode 100644 index 0000000000..5719c062d2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/ord_type.md @@ -0,0 +1,9 @@ +# ord_type_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/order_cancel_all_request.md b/ems-cloud-mgmt-sdk/c/docs/order_cancel_all_request.md new file mode 100644 index 0000000000..88b0c249f2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/order_cancel_all_request.md @@ -0,0 +1,10 @@ +# order_cancel_all_request_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Identifier of the exchange from which active orders should be canceled. | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/order_cancel_single_request.md b/ems-cloud-mgmt-sdk/c/docs/order_cancel_single_request.md new file mode 100644 index 0000000000..b6335467d4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/order_cancel_single_request.md @@ -0,0 +1,12 @@ +# order_cancel_single_request_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Exchange identifier used to identify the routing destination. | +**exchange_order_id** | **char \*** | Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. | [optional] +**client_order_id** | **char \*** | The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/order_execution_report.md b/ems-cloud-mgmt-sdk/c/docs/order_execution_report.md new file mode 100644 index 0000000000..7424187833 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/order_execution_report.md @@ -0,0 +1,29 @@ +# order_execution_report_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Exchange identifier used to identify the routing destination. | +**client_order_id** | **char \*** | The unique identifier of the order assigned by the client. | +**symbol_id_exchange** | **char \*** | Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**symbol_id_coinapi** | **char \*** | CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**amount_order** | **double** | Order quantity. | +**price** | **double** | Order price. | +**side** | **ord_side_t \*** | | +**order_type** | **ord_type_t \*** | | +**time_in_force** | **time_in_force_t \*** | | +**expire_time** | | Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. | [optional] +**exec_inst** | **list_t \*** | Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> | [optional] +**client_order_id_format_exchange** | **char \*** | The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. | +**exchange_order_id** | **char \*** | Unique identifier of the order assigned by the exchange or executing system. | [optional] +**amount_open** | **double** | Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` | +**amount_filled** | **double** | Total quantity filled. | +**avg_px** | **double** | Calculated average price of all fills on this order. | [optional] +**status** | **ord_status_t \*** | | +**status_history** | **list_t \*** | Timestamped history of order status changes. | [optional] +**error_message** | **char \*** | Error message. | [optional] +**fills** | [**list_t**](fills.md) \* | Relay fill information on working orders. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/order_execution_report_all_of.md b/ems-cloud-mgmt-sdk/c/docs/order_execution_report_all_of.md new file mode 100644 index 0000000000..33e9c42203 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/order_execution_report_all_of.md @@ -0,0 +1,18 @@ +# order_execution_report_all_of_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client_order_id_format_exchange** | **char \*** | The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. | +**exchange_order_id** | **char \*** | Unique identifier of the order assigned by the exchange or executing system. | [optional] +**amount_open** | **double** | Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` | +**amount_filled** | **double** | Total quantity filled. | +**avg_px** | **double** | Calculated average price of all fills on this order. | [optional] +**status** | **ord_status_t \*** | | +**status_history** | **list_t \*** | Timestamped history of order status changes. | [optional] +**error_message** | **char \*** | Error message. | [optional] +**fills** | [**list_t**](fills.md) \* | Relay fill information on working orders. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/order_new_single_request.md b/ems-cloud-mgmt-sdk/c/docs/order_new_single_request.md new file mode 100644 index 0000000000..cbde581f77 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/order_new_single_request.md @@ -0,0 +1,20 @@ +# order_new_single_request_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Exchange identifier used to identify the routing destination. | +**client_order_id** | **char \*** | The unique identifier of the order assigned by the client. | +**symbol_id_exchange** | **char \*** | Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**symbol_id_coinapi** | **char \*** | CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. | [optional] +**amount_order** | **double** | Order quantity. | +**price** | **double** | Order price. | +**side** | **ord_side_t \*** | | +**order_type** | **ord_type_t \*** | | +**time_in_force** | **time_in_force_t \*** | | +**expire_time** | | Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. | [optional] +**exec_inst** | **list_t \*** | Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/position.md b/ems-cloud-mgmt-sdk/c/docs/position.md new file mode 100644 index 0000000000..d376645cf0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/position.md @@ -0,0 +1,11 @@ +# position_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exchange_id** | **char \*** | Exchange identifier used to identify the routing destination. | [optional] +**data** | [**list_t**](position_data.md) \* | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/position_data.md b/ems-cloud-mgmt-sdk/c/docs/position_data.md new file mode 100644 index 0000000000..bacf6347f3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/position_data.md @@ -0,0 +1,19 @@ +# position_data_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**symbol_id_exchange** | **char \*** | Exchange symbol. | [optional] +**symbol_id_coinapi** | **char \*** | CoinAPI symbol. | [optional] +**avg_entry_price** | **double** | Calculated average price of all fills on this position. | [optional] +**quantity** | **double** | The current position quantity. | [optional] +**side** | **ord_side_t \*** | | [optional] +**unrealized_pnl** | **double** | Unrealised profit or loss (PNL) of this position. | [optional] +**leverage** | **double** | Leverage for this position reported by the exchange. | [optional] +**cross_margin** | **int** | Is cross margin mode enable for this position? | [optional] +**liquidation_price** | **double** | Liquidation price. If mark price will reach this value, the position will be liquidated. | [optional] +**raw_data** | [**object_t**](.md) \* | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/reject_reason.md b/ems-cloud-mgmt-sdk/c/docs/reject_reason.md new file mode 100644 index 0000000000..16592f957b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/reject_reason.md @@ -0,0 +1,9 @@ +# reject_reason_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/time_in_force.md b/ems-cloud-mgmt-sdk/c/docs/time_in_force.md new file mode 100644 index 0000000000..da0e881801 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/time_in_force.md @@ -0,0 +1,9 @@ +# time_in_force_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/docs/validation_error.md b/ems-cloud-mgmt-sdk/c/docs/validation_error.md new file mode 100644 index 0000000000..cc9e1ca020 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/docs/validation_error.md @@ -0,0 +1,14 @@ +# validation_error_t + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **char \*** | | [optional] +**title** | **char \*** | | [optional] +**status** | **double** | | [optional] +**trace_id** | **char \*** | | [optional] +**errors** | **char \*** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/ems-cloud-mgmt-sdk/c/external/cJSON.c b/ems-cloud-mgmt-sdk/c/external/cJSON.c new file mode 100644 index 0000000000..2139b5efd9 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/external/cJSON.c @@ -0,0 +1,2932 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#define true ((cJSON_bool)1) +#define false ((cJSON_bool)0) + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) { + if (!cJSON_IsString(item)) { + return NULL; + } + + return item->valuestring; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 7) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(*allocate)(size_t size); + void (*deallocate)(void *pointer); + void *(*reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dillimport '...' is not static */ +static void *internal_malloc(size_t size) +{ + return malloc(size); +} +static void internal_free(void *pointer) +{ + free(pointer); +} +static void *internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + if (newbuffer) + { + memcpy(newbuffer, p->buffer, p->offset + 1); + } + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26]; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if ((d * 0) != 0) + { + length = sprintf((char*)number_buffer, "null"); + } + else + { + /* Try 15 decimal places of precision to avoid insignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = strlen((const char*)value) + sizeof(""); + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +#define cjson_min(a, b) ((a < b) ? a : b) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + } + + if (printed != NULL) + { + hooks->deallocate(printed); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, const cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((len < 0) || (buf == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buf; + p.length = (size_t)len; + p.offset = 0; + p.noalloc = true; + p.format = fmt; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* fail to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = (size_t) ((output_buffer->format ? 1 : 0) + (current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL)) + { + return false; + } + + child = array->child; + + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + } + else + { + /* append to the end */ + while (child->next) + { + child = child->next; + } + suffix_object(child, item); + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return; + } + + add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return; + } + + add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL)) + { + return NULL; + } + + if (item->prev != NULL) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0) + { + return; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + add_item_to_array(array, newitem); + return; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (parent->child == item) + { + parent->child = replacement; + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return; + } + + cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + replacement->type &= ~cJSON_StringIsConst; + + cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); + + return true; +} + +CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = b ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0;a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + unsigned char *into = (unsigned char*)json; + + if (json == NULL) + { + return; + } + + while (*json) + { + if (*json == ' ') + { + json++; + } + else if (*json == '\t') + { + /* Whitespace characters. */ + json++; + } + else if (*json == '\r') + { + json++; + } + else if (*json=='\n') + { + json++; + } + else if ((*json == '/') && (json[1] == '/')) + { + /* double-slash comments, to end of line. */ + while (*json && (*json != '\n')) + { + json++; + } + } + else if ((*json == '/') && (json[1] == '*')) + { + /* multiline comments. */ + while (*json && !((*json == '*') && (json[1] == '/'))) + { + json++; + } + json += 2; + } + else if (*json == '\"') + { + /* string literals, which are \" sensitive. */ + *into++ = (unsigned char)*json++; + while (*json && (*json != '\"')) + { + if (*json == '\\') + { + *into++ = (unsigned char)*json++; + } + *into++ = (unsigned char)*json++; + } + *into++ = (unsigned char)*json++; + } + else + { + /* All other characters. */ + *into++ = (unsigned char)*json++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a)) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (a->valuedouble == b->valuedouble) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git a/ems-cloud-mgmt-sdk/c/external/cJSON.h b/ems-cloud-mgmt-sdk/c/external/cJSON.h new file mode 100644 index 0000000000..ab0d0fbace --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/external/cJSON.h @@ -0,0 +1,277 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 7 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 2 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type __stdcall +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type __stdcall +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type __stdcall +#endif +#else /* !WIN32 */ +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check if the item is a string and return its valuestring */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(void) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will +need to be released. With recurse!=0, it will duplicate any children connected to the item. +The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + + +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/ems-cloud-mgmt-sdk/c/external/cJSON.licence b/ems-cloud-mgmt-sdk/c/external/cJSON.licence new file mode 100644 index 0000000000..47234478c1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/external/cJSON.licence @@ -0,0 +1,19 @@ +Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ems-cloud-mgmt-sdk/c/include/apiClient.h b/ems-cloud-mgmt-sdk/c/include/apiClient.h new file mode 100644 index 0000000000..1717994973 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/include/apiClient.h @@ -0,0 +1,61 @@ +#ifndef INCLUDE_API_CLIENT_H +#define INCLUDE_API_CLIENT_H + +#include +#include +#include +#include +#include +#include +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct sslConfig_t { + char *clientCertFile; /* client certificate */ + char *clientKeyFile; /* client private key */ + char *CACertFile; /* CA certificate */ + int insecureSkipTlsVerify ; /* 0 -- verify server certificate */ + /* 1 -- skip ssl verify for server certificate */ +} sslConfig_t; + +typedef struct apiClient_t { + char *basePath; + sslConfig_t *sslConfig; + void *dataReceived; + long dataReceivedLen; + void (*data_callback_func)(void **, long *); + int (*progress_func)(void *, curl_off_t, curl_off_t, curl_off_t, curl_off_t); + void *progress_data; + long response_code; +} apiClient_t; + +apiClient_t* apiClient_create(); + +apiClient_t* apiClient_create_with_base_path(const char *basePath +, sslConfig_t *sslConfig +); + +void apiClient_free(apiClient_t *apiClient); + +void apiClient_invoke(apiClient_t *apiClient,char* operationParameter, list_t *queryParameters, list_t *headerParameters, list_t *formParameters,list_t *headerType,list_t *contentType, char *bodyParameters, char *requestType); + +sslConfig_t *sslConfig_create(const char *clientCertFile, const char *clientKeyFile, const char *CACertFile, int insecureSkipTlsVerify); + +void sslConfig_free(sslConfig_t *sslConfig); + +char *strReplace(char *orig, char *rep, char *with); + +/* + * In single thread program, the function apiClient_setupGlobalEnv is not needed. + * But in multi-thread program, apiClient_setupGlobalEnv must be called before any worker thread is created + */ +void apiClient_setupGlobalEnv(); + +/* + * This function apiClient_unsetupGlobalEnv must be called whether single or multiple program. + * In multi-thread program, it is must be called after all worker threads end. + */ +void apiClient_unsetupGlobalEnv(); + +#endif // INCLUDE_API_CLIENT_H diff --git a/ems-cloud-mgmt-sdk/c/include/binary.h b/ems-cloud-mgmt-sdk/c/include/binary.h new file mode 100644 index 0000000000..571df5b35f --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/include/binary.h @@ -0,0 +1,18 @@ +#ifndef INCLUDE_BINARY_H +#define INCLUDE_BINARY_H + +#include + +typedef struct binary_t +{ + uint8_t* data; + unsigned int len; +} binary_t; + +binary_t* instantiate_binary_t(char* data, int len); + +char *base64encode(const void *b64_encode_this, int encode_this_many_bytes); + +char *base64decode(const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes); + +#endif // INCLUDE_BINARY_H diff --git a/ems-cloud-mgmt-sdk/c/include/keyValuePair.h b/ems-cloud-mgmt-sdk/c/include/keyValuePair.h new file mode 100644 index 0000000000..cb839f29cd --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/include/keyValuePair.h @@ -0,0 +1,17 @@ +#ifndef _keyValuePair_H_ +#define _keyValuePair_H_ + +#include + +typedef struct keyValuePair_t { + char* key; + void* value; +} keyValuePair_t; + +keyValuePair_t *keyValuePair_create(char *key, void *value); + +keyValuePair_t* keyValuePair_create_allocate(char* key, double value); + +void keyValuePair_free(keyValuePair_t *keyValuePair); + +#endif /* _keyValuePair_H_ */ \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/c/include/list.h b/ems-cloud-mgmt-sdk/c/include/list.h new file mode 100644 index 0000000000..96c5832b02 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/include/list.h @@ -0,0 +1,42 @@ +#ifndef INCLUDE_LIST_H +#define INCLUDE_LIST_H + +#include "../external/cJSON.h" +#include "../include/list.h" + +typedef struct list_t list_t; + +typedef struct listEntry_t listEntry_t; + +struct listEntry_t { + listEntry_t* nextListEntry; + listEntry_t* prevListEntry; + void* data; +}; + +typedef struct list_t { + listEntry_t *firstEntry; + listEntry_t *lastEntry; + + long count; +} list_t; + +#define list_ForEach(element, list) for(element = (list != NULL) ? (list)->firstEntry : NULL; element != NULL; element = element->nextListEntry) + +list_t* List(); +void list_freeListList(list_t* listToFree); + +void list_addElement(list_t* list, void* dataToAddInList); +listEntry_t* list_getElementAt(list_t *list, long indexOfElement); +listEntry_t* list_getWithIndex(list_t* list, int index); +void list_removeElement(list_t* list, listEntry_t* elementToRemove); + +void list_iterateThroughListForward(list_t* list, void (*operationToPerform)(listEntry_t*, void*), void *additionalDataNeededForCallbackFunction); +void list_iterateThroughListBackward(list_t* list, void (*operationToPerform)(listEntry_t*, void*), void *additionalDataNeededForCallbackFunction); + +void listEntry_printAsInt(listEntry_t* listEntry, void *additionalData); +void listEntry_free(listEntry_t *listEntry, void *additionalData); + +char* findStrInStrList(list_t* strList, const char* str); +void clear_and_free_string_list(list_t * list); +#endif // INCLUDE_LIST_H diff --git a/ems-cloud-mgmt-sdk/c/libcurl.licence b/ems-cloud-mgmt-sdk/c/libcurl.licence new file mode 100644 index 0000000000..b5f47ac94d --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/libcurl.licence @@ -0,0 +1,11 @@ +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2018, Daniel Stenberg, daniel@haxx.se, and many contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. diff --git a/ems-cloud-mgmt-sdk/c/model/balance.c b/ems-cloud-mgmt-sdk/c/model/balance.c new file mode 100644 index 0000000000..6d424d45ee --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/balance.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include "balance.h" + + + +balance_t *balance_create( + char *exchange_id, + list_t *data + ) { + balance_t *balance_local_var = malloc(sizeof(balance_t)); + if (!balance_local_var) { + return NULL; + } + balance_local_var->exchange_id = exchange_id; + balance_local_var->data = data; + + return balance_local_var; +} + + +void balance_free(balance_t *balance) { + if(NULL == balance){ + return ; + } + listEntry_t *listEntry; + if (balance->exchange_id) { + free(balance->exchange_id); + balance->exchange_id = NULL; + } + if (balance->data) { + list_ForEach(listEntry, balance->data) { + balance_data_free(listEntry->data); + } + list_freeList(balance->data); + balance->data = NULL; + } + free(balance); +} + +cJSON *balance_convertToJSON(balance_t *balance) { + cJSON *item = cJSON_CreateObject(); + + // balance->exchange_id + if(balance->exchange_id) { + if(cJSON_AddStringToObject(item, "exchange_id", balance->exchange_id) == NULL) { + goto fail; //String + } + } + + + // balance->data + if(balance->data) { + cJSON *data = cJSON_AddArrayToObject(item, "data"); + if(data == NULL) { + goto fail; //nonprimitive container + } + + listEntry_t *dataListEntry; + if (balance->data) { + list_ForEach(dataListEntry, balance->data) { + cJSON *itemLocal = balance_data_convertToJSON(dataListEntry->data); + if(itemLocal == NULL) { + goto fail; + } + cJSON_AddItemToArray(data, itemLocal); + } + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +balance_t *balance_parseFromJSON(cJSON *balanceJSON){ + + balance_t *balance_local_var = NULL; + + // balance->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(balanceJSON, "exchange_id"); + if (exchange_id) { + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + } + + // balance->data + cJSON *data = cJSON_GetObjectItemCaseSensitive(balanceJSON, "data"); + list_t *dataList; + if (data) { + cJSON *data_local_nonprimitive; + if(!cJSON_IsArray(data)){ + goto end; //nonprimitive container + } + + dataList = list_createList(); + + cJSON_ArrayForEach(data_local_nonprimitive,data ) + { + if(!cJSON_IsObject(data_local_nonprimitive)){ + goto end; + } + balance_data_t *dataItem = balance_data_parseFromJSON(data_local_nonprimitive); + + list_addElement(dataList, dataItem); + } + } + + + balance_local_var = balance_create ( + exchange_id ? strdup(exchange_id->valuestring) : NULL, + data ? dataList : NULL + ); + + return balance_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/balance.h b/ems-cloud-mgmt-sdk/c/model/balance.h new file mode 100644 index 0000000000..450c3620f6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/balance.h @@ -0,0 +1,40 @@ +/* + * balance.h + * + * + */ + +#ifndef _balance_H_ +#define _balance_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct balance_t balance_t; + +#include "balance_data.h" + + + +typedef struct balance_t { + char *exchange_id; // string + list_t *data; //nonprimitive container + +} balance_t; + +balance_t *balance_create( + char *exchange_id, + list_t *data +); + +void balance_free(balance_t *balance); + +balance_t *balance_parseFromJSON(cJSON *balanceJSON); + +cJSON *balance_convertToJSON(balance_t *balance); + +#endif /* _balance_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/balance_data.c b/ems-cloud-mgmt-sdk/c/model/balance_data.c new file mode 100644 index 0000000000..3da642be55 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/balance_data.c @@ -0,0 +1,237 @@ +#include +#include +#include +#include "balance_data.h" + + +char* last_updated_bybalance_data_ToString(ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_by) { + char* last_updated_byArray[] = { "NULL", "INITIALIZATION", "BALANCE_MANAGER", "EXCHANGE" }; + return last_updated_byArray[last_updated_by]; +} + +ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_bybalance_data_FromString(char* last_updated_by){ + int stringToReturn = 0; + char *last_updated_byArray[] = { "NULL", "INITIALIZATION", "BALANCE_MANAGER", "EXCHANGE" }; + size_t sizeofArray = sizeof(last_updated_byArray) / sizeof(last_updated_byArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(last_updated_by, last_updated_byArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +balance_data_t *balance_data_create( + char *asset_id_exchange, + char *asset_id_coinapi, + double balance, + double available, + double locked, + ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_by, + double rate_usd, + double traded + ) { + balance_data_t *balance_data_local_var = malloc(sizeof(balance_data_t)); + if (!balance_data_local_var) { + return NULL; + } + balance_data_local_var->asset_id_exchange = asset_id_exchange; + balance_data_local_var->asset_id_coinapi = asset_id_coinapi; + balance_data_local_var->balance = balance; + balance_data_local_var->available = available; + balance_data_local_var->locked = locked; + balance_data_local_var->last_updated_by = last_updated_by; + balance_data_local_var->rate_usd = rate_usd; + balance_data_local_var->traded = traded; + + return balance_data_local_var; +} + + +void balance_data_free(balance_data_t *balance_data) { + if(NULL == balance_data){ + return ; + } + listEntry_t *listEntry; + if (balance_data->asset_id_exchange) { + free(balance_data->asset_id_exchange); + balance_data->asset_id_exchange = NULL; + } + if (balance_data->asset_id_coinapi) { + free(balance_data->asset_id_coinapi); + balance_data->asset_id_coinapi = NULL; + } + free(balance_data); +} + +cJSON *balance_data_convertToJSON(balance_data_t *balance_data) { + cJSON *item = cJSON_CreateObject(); + + // balance_data->asset_id_exchange + if(balance_data->asset_id_exchange) { + if(cJSON_AddStringToObject(item, "asset_id_exchange", balance_data->asset_id_exchange) == NULL) { + goto fail; //String + } + } + + + // balance_data->asset_id_coinapi + if(balance_data->asset_id_coinapi) { + if(cJSON_AddStringToObject(item, "asset_id_coinapi", balance_data->asset_id_coinapi) == NULL) { + goto fail; //String + } + } + + + // balance_data->balance + if(balance_data->balance) { + if(cJSON_AddNumberToObject(item, "balance", balance_data->balance) == NULL) { + goto fail; //Numeric + } + } + + + // balance_data->available + if(balance_data->available) { + if(cJSON_AddNumberToObject(item, "available", balance_data->available) == NULL) { + goto fail; //Numeric + } + } + + + // balance_data->locked + if(balance_data->locked) { + if(cJSON_AddNumberToObject(item, "locked", balance_data->locked) == NULL) { + goto fail; //Numeric + } + } + + + // balance_data->last_updated_by + + if(cJSON_AddStringToObject(item, "last_updated_by", last_updated_bybalance_data_ToString(balance_data->last_updated_by)) == NULL) + { + goto fail; //Enum + } + + + + // balance_data->rate_usd + if(balance_data->rate_usd) { + if(cJSON_AddNumberToObject(item, "rate_usd", balance_data->rate_usd) == NULL) { + goto fail; //Numeric + } + } + + + // balance_data->traded + if(balance_data->traded) { + if(cJSON_AddNumberToObject(item, "traded", balance_data->traded) == NULL) { + goto fail; //Numeric + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +balance_data_t *balance_data_parseFromJSON(cJSON *balance_dataJSON){ + + balance_data_t *balance_data_local_var = NULL; + + // balance_data->asset_id_exchange + cJSON *asset_id_exchange = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "asset_id_exchange"); + if (asset_id_exchange) { + if(!cJSON_IsString(asset_id_exchange)) + { + goto end; //String + } + } + + // balance_data->asset_id_coinapi + cJSON *asset_id_coinapi = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "asset_id_coinapi"); + if (asset_id_coinapi) { + if(!cJSON_IsString(asset_id_coinapi)) + { + goto end; //String + } + } + + // balance_data->balance + cJSON *balance = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "balance"); + if (balance) { + if(!cJSON_IsNumber(balance)) + { + goto end; //Numeric + } + } + + // balance_data->available + cJSON *available = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "available"); + if (available) { + if(!cJSON_IsNumber(available)) + { + goto end; //Numeric + } + } + + // balance_data->locked + cJSON *locked = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "locked"); + if (locked) { + if(!cJSON_IsNumber(locked)) + { + goto end; //Numeric + } + } + + // balance_data->last_updated_by + cJSON *last_updated_by = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "last_updated_by"); + ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_byVariable; + if (last_updated_by) { + if(!cJSON_IsString(last_updated_by)) + { + goto end; //Enum + } + last_updated_byVariable = last_updated_bybalance_data_FromString(last_updated_by->valuestring); + } + + // balance_data->rate_usd + cJSON *rate_usd = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "rate_usd"); + if (rate_usd) { + if(!cJSON_IsNumber(rate_usd)) + { + goto end; //Numeric + } + } + + // balance_data->traded + cJSON *traded = cJSON_GetObjectItemCaseSensitive(balance_dataJSON, "traded"); + if (traded) { + if(!cJSON_IsNumber(traded)) + { + goto end; //Numeric + } + } + + + balance_data_local_var = balance_data_create ( + asset_id_exchange ? strdup(asset_id_exchange->valuestring) : NULL, + asset_id_coinapi ? strdup(asset_id_coinapi->valuestring) : NULL, + balance ? balance->valuedouble : 0, + available ? available->valuedouble : 0, + locked ? locked->valuedouble : 0, + last_updated_by ? last_updated_byVariable : -1, + rate_usd ? rate_usd->valuedouble : 0, + traded ? traded->valuedouble : 0 + ); + + return balance_data_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/balance_data.h b/ems-cloud-mgmt-sdk/c/model/balance_data.h new file mode 100644 index 0000000000..8db404425c --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/balance_data.h @@ -0,0 +1,59 @@ +/* + * balance_data.h + * + * + */ + +#ifndef _balance_data_H_ +#define _balance_data_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct balance_data_t balance_data_t; + + +// Enum LASTUPDATEDBY for balance_data + +typedef enum { ems___rest_api_balance_data_LASTUPDATEDBY_NULL = 0, ems___rest_api_balance_data_LASTUPDATEDBY_INITIALIZATION, ems___rest_api_balance_data_LASTUPDATEDBY_BALANCE_MANAGER, ems___rest_api_balance_data_LASTUPDATEDBY_EXCHANGE } ems___rest_api_balance_data_LASTUPDATEDBY_e; + +char* balance_data_last_updated_by_ToString(ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_by); + +ems___rest_api_balance_data_LASTUPDATEDBY_e balance_data_last_updated_by_FromString(char* last_updated_by); + + + +typedef struct balance_data_t { + char *asset_id_exchange; // string + char *asset_id_coinapi; // string + double balance; //numeric + double available; //numeric + double locked; //numeric + ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_by; //enum + double rate_usd; //numeric + double traded; //numeric + +} balance_data_t; + +balance_data_t *balance_data_create( + char *asset_id_exchange, + char *asset_id_coinapi, + double balance, + double available, + double locked, + ems___rest_api_balance_data_LASTUPDATEDBY_e last_updated_by, + double rate_usd, + double traded +); + +void balance_data_free(balance_data_t *balance_data); + +balance_data_t *balance_data_parseFromJSON(cJSON *balance_dataJSON); + +cJSON *balance_data_convertToJSON(balance_data_t *balance_data); + +#endif /* _balance_data_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/fills.c b/ems-cloud-mgmt-sdk/c/model/fills.c new file mode 100644 index 0000000000..0c6d70dea6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/fills.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include "fills.h" + + + +fills_t *fills_create( + double price, + double amount + ) { + fills_t *fills_local_var = malloc(sizeof(fills_t)); + if (!fills_local_var) { + return NULL; + } + fills_local_var->time = time; + fills_local_var->price = price; + fills_local_var->amount = amount; + + return fills_local_var; +} + + +void fills_free(fills_t *fills) { + if(NULL == fills){ + return ; + } + listEntry_t *listEntry; + free(fills); +} + +cJSON *fills_convertToJSON(fills_t *fills) { + cJSON *item = cJSON_CreateObject(); + + // fills->time + if(fills->time) { + } + + + // fills->price + if(fills->price) { + if(cJSON_AddNumberToObject(item, "price", fills->price) == NULL) { + goto fail; //Numeric + } + } + + + // fills->amount + if(fills->amount) { + if(cJSON_AddNumberToObject(item, "amount", fills->amount) == NULL) { + goto fail; //Numeric + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +fills_t *fills_parseFromJSON(cJSON *fillsJSON){ + + fills_t *fills_local_var = NULL; + + // fills->time + cJSON *time = cJSON_GetObjectItemCaseSensitive(fillsJSON, "time"); + } + + // fills->price + cJSON *price = cJSON_GetObjectItemCaseSensitive(fillsJSON, "price"); + if (price) { + if(!cJSON_IsNumber(price)) + { + goto end; //Numeric + } + } + + // fills->amount + cJSON *amount = cJSON_GetObjectItemCaseSensitive(fillsJSON, "amount"); + if (amount) { + if(!cJSON_IsNumber(amount)) + { + goto end; //Numeric + } + } + + + fills_local_var = fills_create ( + price ? price->valuedouble : 0, + amount ? amount->valuedouble : 0 + ); + + return fills_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/fills.h b/ems-cloud-mgmt-sdk/c/model/fills.h new file mode 100644 index 0000000000..d632abd812 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/fills.h @@ -0,0 +1,39 @@ +/* + * fills.h + * + * + */ + +#ifndef _fills_H_ +#define _fills_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct fills_t fills_t; + + + + +typedef struct fills_t { + double price; //numeric + double amount; //numeric + +} fills_t; + +fills_t *fills_create( + double price, + double amount +); + +void fills_free(fills_t *fills); + +fills_t *fills_parseFromJSON(cJSON *fillsJSON); + +cJSON *fills_convertToJSON(fills_t *fills); + +#endif /* _fills_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/message_reject.c b/ems-cloud-mgmt-sdk/c/model/message_reject.c new file mode 100644 index 0000000000..33711e6851 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/message_reject.c @@ -0,0 +1,195 @@ +#include +#include +#include +#include "message_reject.h" + + +char* reject_reasonmessage_reject_ToString(ems___rest_api_message_reject__e reject_reason) { + char* reject_reasonArray[] = { "NULL", "OTHER", "EXCHANGE_UNREACHABLE", "EXCHANGE_RESPONSE_TIMEOUT", "ORDER_ID_NOT_FOUND", "INVALID_TYPE", "METHOD_NOT_SUPPORTED", "JSON_ERROR" }; + return reject_reasonArray[reject_reason]; +} + +ems___rest_api_message_reject__e reject_reasonmessage_reject_FromString(char* reject_reason){ + int stringToReturn = 0; + char *reject_reasonArray[] = { "NULL", "OTHER", "EXCHANGE_UNREACHABLE", "EXCHANGE_RESPONSE_TIMEOUT", "ORDER_ID_NOT_FOUND", "INVALID_TYPE", "METHOD_NOT_SUPPORTED", "JSON_ERROR" }; + size_t sizeofArray = sizeof(reject_reasonArray) / sizeof(reject_reasonArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(reject_reason, reject_reasonArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +message_reject_t *message_reject_create( + char *type, + reject_reason_t *reject_reason, + char *exchange_id, + char *message, + char *rejected_message + ) { + message_reject_t *message_reject_local_var = malloc(sizeof(message_reject_t)); + if (!message_reject_local_var) { + return NULL; + } + message_reject_local_var->type = type; + message_reject_local_var->reject_reason = reject_reason; + message_reject_local_var->exchange_id = exchange_id; + message_reject_local_var->message = message; + message_reject_local_var->rejected_message = rejected_message; + + return message_reject_local_var; +} + + +void message_reject_free(message_reject_t *message_reject) { + if(NULL == message_reject){ + return ; + } + listEntry_t *listEntry; + if (message_reject->type) { + free(message_reject->type); + message_reject->type = NULL; + } + if (message_reject->reject_reason) { + reject_reason_free(message_reject->reject_reason); + message_reject->reject_reason = NULL; + } + if (message_reject->exchange_id) { + free(message_reject->exchange_id); + message_reject->exchange_id = NULL; + } + if (message_reject->message) { + free(message_reject->message); + message_reject->message = NULL; + } + if (message_reject->rejected_message) { + free(message_reject->rejected_message); + message_reject->rejected_message = NULL; + } + free(message_reject); +} + +cJSON *message_reject_convertToJSON(message_reject_t *message_reject) { + cJSON *item = cJSON_CreateObject(); + + // message_reject->type + if(message_reject->type) { + if(cJSON_AddStringToObject(item, "type", message_reject->type) == NULL) { + goto fail; //String + } + } + + + // message_reject->reject_reason + + cJSON *reject_reason_local_JSON = reject_reason_convertToJSON(message_reject->reject_reason); + if(reject_reason_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "reject_reason", reject_reason_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + + // message_reject->exchange_id + if(message_reject->exchange_id) { + if(cJSON_AddStringToObject(item, "exchange_id", message_reject->exchange_id) == NULL) { + goto fail; //String + } + } + + + // message_reject->message + if(message_reject->message) { + if(cJSON_AddStringToObject(item, "message", message_reject->message) == NULL) { + goto fail; //String + } + } + + + // message_reject->rejected_message + if(message_reject->rejected_message) { + if(cJSON_AddStringToObject(item, "rejected_message", message_reject->rejected_message) == NULL) { + goto fail; //String + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +message_reject_t *message_reject_parseFromJSON(cJSON *message_rejectJSON){ + + message_reject_t *message_reject_local_var = NULL; + + // define the local variable for message_reject->reject_reason + reject_reason_t *reject_reason_local_nonprim = NULL; + + // message_reject->type + cJSON *type = cJSON_GetObjectItemCaseSensitive(message_rejectJSON, "type"); + if (type) { + if(!cJSON_IsString(type)) + { + goto end; //String + } + } + + // message_reject->reject_reason + cJSON *reject_reason = cJSON_GetObjectItemCaseSensitive(message_rejectJSON, "reject_reason"); + if (reject_reason) { + reject_reason_local_nonprim = reject_reason_parseFromJSON(reject_reason); //custom + } + + // message_reject->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(message_rejectJSON, "exchange_id"); + if (exchange_id) { + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + } + + // message_reject->message + cJSON *message = cJSON_GetObjectItemCaseSensitive(message_rejectJSON, "message"); + if (message) { + if(!cJSON_IsString(message)) + { + goto end; //String + } + } + + // message_reject->rejected_message + cJSON *rejected_message = cJSON_GetObjectItemCaseSensitive(message_rejectJSON, "rejected_message"); + if (rejected_message) { + if(!cJSON_IsString(rejected_message)) + { + goto end; //String + } + } + + + message_reject_local_var = message_reject_create ( + type ? strdup(type->valuestring) : NULL, + reject_reason ? reject_reason_local_nonprim : NULL, + exchange_id ? strdup(exchange_id->valuestring) : NULL, + message ? strdup(message->valuestring) : NULL, + rejected_message ? strdup(rejected_message->valuestring) : NULL + ); + + return message_reject_local_var; +end: + if (reject_reason_local_nonprim) { + reject_reason_free(reject_reason_local_nonprim); + reject_reason_local_nonprim = NULL; + } + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/message_reject.h b/ems-cloud-mgmt-sdk/c/model/message_reject.h new file mode 100644 index 0000000000..26d2c9a215 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/message_reject.h @@ -0,0 +1,54 @@ +/* + * message_reject.h + * + * + */ + +#ifndef _message_reject_H_ +#define _message_reject_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct message_reject_t message_reject_t; + +#include "reject_reason.h" + +// Enum for message_reject + +typedef enum { ems___rest_api_message_reject__NULL = 0, ems___rest_api_message_reject__OTHER, ems___rest_api_message_reject__EXCHANGE_UNREACHABLE, ems___rest_api_message_reject__EXCHANGE_RESPONSE_TIMEOUT, ems___rest_api_message_reject__ORDER_ID_NOT_FOUND, ems___rest_api_message_reject__INVALID_TYPE, ems___rest_api_message_reject__METHOD_NOT_SUPPORTED, ems___rest_api_message_reject__JSON_ERROR } ems___rest_api_message_reject__e; + +char* message_reject_reject_reason_ToString(ems___rest_api_message_reject__e reject_reason); + +ems___rest_api_message_reject__e message_reject_reject_reason_FromString(char* reject_reason); + + + +typedef struct message_reject_t { + char *type; // string + reject_reason_t *reject_reason; // custom + char *exchange_id; // string + char *message; // string + char *rejected_message; // string + +} message_reject_t; + +message_reject_t *message_reject_create( + char *type, + reject_reason_t *reject_reason, + char *exchange_id, + char *message, + char *rejected_message +); + +void message_reject_free(message_reject_t *message_reject); + +message_reject_t *message_reject_parseFromJSON(cJSON *message_rejectJSON); + +cJSON *message_reject_convertToJSON(message_reject_t *message_reject); + +#endif /* _message_reject_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/object.c b/ems-cloud-mgmt-sdk/c/model/object.c new file mode 100644 index 0000000000..d106693842 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/object.c @@ -0,0 +1,31 @@ +#include +#include +#include +#include "object.h" + +object_t *object_create() { + object_t *object = malloc(sizeof(object_t)); + + return object; +} + +void object_free(object_t *object) { + free (object); +} + +cJSON *object_convertToJSON(object_t *object) { + cJSON *item = cJSON_CreateObject(); + + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +object_t *object_parseFromJSON(char *jsonString){ + object_t *object = NULL; + + return object; +end: + return NULL; +} diff --git a/ems-cloud-mgmt-sdk/c/model/object.h b/ems-cloud-mgmt-sdk/c/model/object.h new file mode 100644 index 0000000000..18503e0c27 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/object.h @@ -0,0 +1,27 @@ +/* + * object.h + */ + +#ifndef _object_H_ +#define _object_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + + +typedef struct object_t { + void *temporary; +} object_t; + +object_t *object_create(); + +void object_free(object_t *object); + +object_t *object_parseFromJSON(char *jsonString); + +cJSON *object_convertToJSON(object_t *object); + +#endif /* _object_H_ */ diff --git a/ems-cloud-mgmt-sdk/c/model/ord_side.c b/ems-cloud-mgmt-sdk/c/model/ord_side.c new file mode 100644 index 0000000000..d14469311b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_side.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "ord_side.h" + + +char* ord_side_ord_side_ToString(ems___rest_api_ord_side__e ord_side) { + char *ord_sideArray[] = { "NULL", "BUY", "SELL" }; + return ord_sideArray[ord_side]; +} + +ems___rest_api_ord_side__e ord_side_ord_side_FromString(char* ord_side) { + int stringToReturn = 0; + char *ord_sideArray[] = { "NULL", "BUY", "SELL" }; + size_t sizeofArray = sizeof(ord_sideArray) / sizeof(ord_sideArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(ord_side, ord_sideArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +cJSON *ord_side_ord_side_convertToJSON(ems___rest_api_ord_side__e ord_side) { + cJSON *item = cJSON_CreateObject(); + if(cJSON_AddStringToObject(item, "ord_side", ord_side_ord_side_ToString(ord_side)) == NULL) { + goto fail; + } + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +ems___rest_api_ord_side__e ord_side_ord_side_parseFromJSON(cJSON *ord_sideJSON) { + ems___rest_api_ord_side__e *ord_side = NULL; + ems___rest_api_ord_side__e ord_sideVariable; + cJSON *ord_sideVar = cJSON_GetObjectItemCaseSensitive(ord_sideJSON, "ord_side"); + if(!cJSON_IsString(ord_sideVar) || (ord_sideVar->valuestring == NULL)){ + goto end; + } + ord_sideVariable = ord_side_ord_side_FromString(ord_sideVar->valuestring); + return ord_sideVariable; +end: + return 0; +} diff --git a/ems-cloud-mgmt-sdk/c/model/ord_side.h b/ems-cloud-mgmt-sdk/c/model/ord_side.h new file mode 100644 index 0000000000..2ee99ba6bf --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_side.h @@ -0,0 +1,32 @@ +/* + * ord_side.h + * + * Side of order. + */ + +#ifndef _ord_side_H_ +#define _ord_side_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct ord_side_t ord_side_t; + + +// Enum for ord_side + +typedef enum { ems___rest_api_ord_side__NULL = 0, ems___rest_api_ord_side__BUY, ems___rest_api_ord_side__SELL } ems___rest_api_ord_side__e; + +char* ord_side_ord_side_ToString(ems___rest_api_ord_side__e ord_side); + +ems___rest_api_ord_side__e ord_side_ord_side_FromString(char* ord_side); + +//cJSON *ord_side_ord_side_convertToJSON(ems___rest_api_ord_side__e ord_side); + +//ems___rest_api_ord_side__e ord_side_ord_side_parseFromJSON(cJSON *ord_sideJSON); + +#endif /* _ord_side_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/ord_status.c b/ems-cloud-mgmt-sdk/c/model/ord_status.c new file mode 100644 index 0000000000..d9c5c45557 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_status.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "ord_status.h" + + +char* ord_status_ord_status_ToString(ems___rest_api_ord_status__e ord_status) { + char *ord_statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + return ord_statusArray[ord_status]; +} + +ems___rest_api_ord_status__e ord_status_ord_status_FromString(char* ord_status) { + int stringToReturn = 0; + char *ord_statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + size_t sizeofArray = sizeof(ord_statusArray) / sizeof(ord_statusArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(ord_status, ord_statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +cJSON *ord_status_ord_status_convertToJSON(ems___rest_api_ord_status__e ord_status) { + cJSON *item = cJSON_CreateObject(); + if(cJSON_AddStringToObject(item, "ord_status", ord_status_ord_status_ToString(ord_status)) == NULL) { + goto fail; + } + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +ems___rest_api_ord_status__e ord_status_ord_status_parseFromJSON(cJSON *ord_statusJSON) { + ems___rest_api_ord_status__e *ord_status = NULL; + ems___rest_api_ord_status__e ord_statusVariable; + cJSON *ord_statusVar = cJSON_GetObjectItemCaseSensitive(ord_statusJSON, "ord_status"); + if(!cJSON_IsString(ord_statusVar) || (ord_statusVar->valuestring == NULL)){ + goto end; + } + ord_statusVariable = ord_status_ord_status_FromString(ord_statusVar->valuestring); + return ord_statusVariable; +end: + return 0; +} diff --git a/ems-cloud-mgmt-sdk/c/model/ord_status.h b/ems-cloud-mgmt-sdk/c/model/ord_status.h new file mode 100644 index 0000000000..ca18c89147 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_status.h @@ -0,0 +1,32 @@ +/* + * ord_status.h + * + * Order statuses and the lifecycle are documented in the separate section: <a href=\"#ems-order-lifecycle\">EMS / Starter Guide / Order Lifecycle</a> + */ + +#ifndef _ord_status_H_ +#define _ord_status_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct ord_status_t ord_status_t; + + +// Enum for ord_status + +typedef enum { ems___rest_api_ord_status__NULL = 0, ems___rest_api_ord_status__RECEIVED, ems___rest_api_ord_status__ROUTING, ems___rest_api_ord_status__ROUTED, ems___rest_api_ord_status___NEW, ems___rest_api_ord_status__PENDING_CANCEL, ems___rest_api_ord_status__PARTIALLY_FILLED, ems___rest_api_ord_status__FILLED, ems___rest_api_ord_status__CANCELED, ems___rest_api_ord_status__REJECTED } ems___rest_api_ord_status__e; + +char* ord_status_ord_status_ToString(ems___rest_api_ord_status__e ord_status); + +ems___rest_api_ord_status__e ord_status_ord_status_FromString(char* ord_status); + +//cJSON *ord_status_ord_status_convertToJSON(ems___rest_api_ord_status__e ord_status); + +//ems___rest_api_ord_status__e ord_status_ord_status_parseFromJSON(cJSON *ord_statusJSON); + +#endif /* _ord_status_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/ord_type.c b/ems-cloud-mgmt-sdk/c/model/ord_type.c new file mode 100644 index 0000000000..f8542ca2a0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_type.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "ord_type.h" + + +char* ord_type_ord_type_ToString(ems___rest_api_ord_type__e ord_type) { + char *ord_typeArray[] = { "NULL", "LIMIT" }; + return ord_typeArray[ord_type]; +} + +ems___rest_api_ord_type__e ord_type_ord_type_FromString(char* ord_type) { + int stringToReturn = 0; + char *ord_typeArray[] = { "NULL", "LIMIT" }; + size_t sizeofArray = sizeof(ord_typeArray) / sizeof(ord_typeArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(ord_type, ord_typeArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +cJSON *ord_type_ord_type_convertToJSON(ems___rest_api_ord_type__e ord_type) { + cJSON *item = cJSON_CreateObject(); + if(cJSON_AddStringToObject(item, "ord_type", ord_type_ord_type_ToString(ord_type)) == NULL) { + goto fail; + } + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +ems___rest_api_ord_type__e ord_type_ord_type_parseFromJSON(cJSON *ord_typeJSON) { + ems___rest_api_ord_type__e *ord_type = NULL; + ems___rest_api_ord_type__e ord_typeVariable; + cJSON *ord_typeVar = cJSON_GetObjectItemCaseSensitive(ord_typeJSON, "ord_type"); + if(!cJSON_IsString(ord_typeVar) || (ord_typeVar->valuestring == NULL)){ + goto end; + } + ord_typeVariable = ord_type_ord_type_FromString(ord_typeVar->valuestring); + return ord_typeVariable; +end: + return 0; +} diff --git a/ems-cloud-mgmt-sdk/c/model/ord_type.h b/ems-cloud-mgmt-sdk/c/model/ord_type.h new file mode 100644 index 0000000000..dec2a436a0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/ord_type.h @@ -0,0 +1,32 @@ +/* + * ord_type.h + * + * Order types are documented in the separate section: <a href=\"#ems-order-params-type\">EMS / Starter Guide / Order parameters / Order type</a> + */ + +#ifndef _ord_type_H_ +#define _ord_type_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct ord_type_t ord_type_t; + + +// Enum for ord_type + +typedef enum { ems___rest_api_ord_type__NULL = 0, ems___rest_api_ord_type__LIMIT } ems___rest_api_ord_type__e; + +char* ord_type_ord_type_ToString(ems___rest_api_ord_type__e ord_type); + +ems___rest_api_ord_type__e ord_type_ord_type_FromString(char* ord_type); + +//cJSON *ord_type_ord_type_convertToJSON(ems___rest_api_ord_type__e ord_type); + +//ems___rest_api_ord_type__e ord_type_ord_type_parseFromJSON(cJSON *ord_typeJSON); + +#endif /* _ord_type_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.c b/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.c new file mode 100644 index 0000000000..8b6ad1728c --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.c @@ -0,0 +1,78 @@ +#include +#include +#include +#include "order_cancel_all_request.h" + + + +order_cancel_all_request_t *order_cancel_all_request_create( + char *exchange_id + ) { + order_cancel_all_request_t *order_cancel_all_request_local_var = malloc(sizeof(order_cancel_all_request_t)); + if (!order_cancel_all_request_local_var) { + return NULL; + } + order_cancel_all_request_local_var->exchange_id = exchange_id; + + return order_cancel_all_request_local_var; +} + + +void order_cancel_all_request_free(order_cancel_all_request_t *order_cancel_all_request) { + if(NULL == order_cancel_all_request){ + return ; + } + listEntry_t *listEntry; + if (order_cancel_all_request->exchange_id) { + free(order_cancel_all_request->exchange_id); + order_cancel_all_request->exchange_id = NULL; + } + free(order_cancel_all_request); +} + +cJSON *order_cancel_all_request_convertToJSON(order_cancel_all_request_t *order_cancel_all_request) { + cJSON *item = cJSON_CreateObject(); + + // order_cancel_all_request->exchange_id + if (!order_cancel_all_request->exchange_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "exchange_id", order_cancel_all_request->exchange_id) == NULL) { + goto fail; //String + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_cancel_all_request_t *order_cancel_all_request_parseFromJSON(cJSON *order_cancel_all_requestJSON){ + + order_cancel_all_request_t *order_cancel_all_request_local_var = NULL; + + // order_cancel_all_request->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(order_cancel_all_requestJSON, "exchange_id"); + if (!exchange_id) { + goto end; + } + + + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + + + order_cancel_all_request_local_var = order_cancel_all_request_create ( + strdup(exchange_id->valuestring) + ); + + return order_cancel_all_request_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.h b/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.h new file mode 100644 index 0000000000..9bc5036d92 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_cancel_all_request.h @@ -0,0 +1,37 @@ +/* + * order_cancel_all_request.h + * + * Cancel all orders request object. + */ + +#ifndef _order_cancel_all_request_H_ +#define _order_cancel_all_request_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct order_cancel_all_request_t order_cancel_all_request_t; + + + + +typedef struct order_cancel_all_request_t { + char *exchange_id; // string + +} order_cancel_all_request_t; + +order_cancel_all_request_t *order_cancel_all_request_create( + char *exchange_id +); + +void order_cancel_all_request_free(order_cancel_all_request_t *order_cancel_all_request); + +order_cancel_all_request_t *order_cancel_all_request_parseFromJSON(cJSON *order_cancel_all_requestJSON); + +cJSON *order_cancel_all_request_convertToJSON(order_cancel_all_request_t *order_cancel_all_request); + +#endif /* _order_cancel_all_request_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.c b/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.c new file mode 100644 index 0000000000..f8ec07fa55 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.c @@ -0,0 +1,126 @@ +#include +#include +#include +#include "order_cancel_single_request.h" + + + +order_cancel_single_request_t *order_cancel_single_request_create( + char *exchange_id, + char *exchange_order_id, + char *client_order_id + ) { + order_cancel_single_request_t *order_cancel_single_request_local_var = malloc(sizeof(order_cancel_single_request_t)); + if (!order_cancel_single_request_local_var) { + return NULL; + } + order_cancel_single_request_local_var->exchange_id = exchange_id; + order_cancel_single_request_local_var->exchange_order_id = exchange_order_id; + order_cancel_single_request_local_var->client_order_id = client_order_id; + + return order_cancel_single_request_local_var; +} + + +void order_cancel_single_request_free(order_cancel_single_request_t *order_cancel_single_request) { + if(NULL == order_cancel_single_request){ + return ; + } + listEntry_t *listEntry; + if (order_cancel_single_request->exchange_id) { + free(order_cancel_single_request->exchange_id); + order_cancel_single_request->exchange_id = NULL; + } + if (order_cancel_single_request->exchange_order_id) { + free(order_cancel_single_request->exchange_order_id); + order_cancel_single_request->exchange_order_id = NULL; + } + if (order_cancel_single_request->client_order_id) { + free(order_cancel_single_request->client_order_id); + order_cancel_single_request->client_order_id = NULL; + } + free(order_cancel_single_request); +} + +cJSON *order_cancel_single_request_convertToJSON(order_cancel_single_request_t *order_cancel_single_request) { + cJSON *item = cJSON_CreateObject(); + + // order_cancel_single_request->exchange_id + if (!order_cancel_single_request->exchange_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "exchange_id", order_cancel_single_request->exchange_id) == NULL) { + goto fail; //String + } + + + // order_cancel_single_request->exchange_order_id + if(order_cancel_single_request->exchange_order_id) { + if(cJSON_AddStringToObject(item, "exchange_order_id", order_cancel_single_request->exchange_order_id) == NULL) { + goto fail; //String + } + } + + + // order_cancel_single_request->client_order_id + if(order_cancel_single_request->client_order_id) { + if(cJSON_AddStringToObject(item, "client_order_id", order_cancel_single_request->client_order_id) == NULL) { + goto fail; //String + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_cancel_single_request_t *order_cancel_single_request_parseFromJSON(cJSON *order_cancel_single_requestJSON){ + + order_cancel_single_request_t *order_cancel_single_request_local_var = NULL; + + // order_cancel_single_request->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(order_cancel_single_requestJSON, "exchange_id"); + if (!exchange_id) { + goto end; + } + + + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + + // order_cancel_single_request->exchange_order_id + cJSON *exchange_order_id = cJSON_GetObjectItemCaseSensitive(order_cancel_single_requestJSON, "exchange_order_id"); + if (exchange_order_id) { + if(!cJSON_IsString(exchange_order_id)) + { + goto end; //String + } + } + + // order_cancel_single_request->client_order_id + cJSON *client_order_id = cJSON_GetObjectItemCaseSensitive(order_cancel_single_requestJSON, "client_order_id"); + if (client_order_id) { + if(!cJSON_IsString(client_order_id)) + { + goto end; //String + } + } + + + order_cancel_single_request_local_var = order_cancel_single_request_create ( + strdup(exchange_id->valuestring), + exchange_order_id ? strdup(exchange_order_id->valuestring) : NULL, + client_order_id ? strdup(client_order_id->valuestring) : NULL + ); + + return order_cancel_single_request_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.h b/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.h new file mode 100644 index 0000000000..0d400815a6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_cancel_single_request.h @@ -0,0 +1,41 @@ +/* + * order_cancel_single_request.h + * + * Cancel single order request object. + */ + +#ifndef _order_cancel_single_request_H_ +#define _order_cancel_single_request_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct order_cancel_single_request_t order_cancel_single_request_t; + + + + +typedef struct order_cancel_single_request_t { + char *exchange_id; // string + char *exchange_order_id; // string + char *client_order_id; // string + +} order_cancel_single_request_t; + +order_cancel_single_request_t *order_cancel_single_request_create( + char *exchange_id, + char *exchange_order_id, + char *client_order_id +); + +void order_cancel_single_request_free(order_cancel_single_request_t *order_cancel_single_request); + +order_cancel_single_request_t *order_cancel_single_request_parseFromJSON(cJSON *order_cancel_single_requestJSON); + +cJSON *order_cancel_single_request_convertToJSON(order_cancel_single_request_t *order_cancel_single_request); + +#endif /* _order_cancel_single_request_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/order_execution_report.c b/ems-cloud-mgmt-sdk/c/model/order_execution_report.c new file mode 100644 index 0000000000..ad3b0780ef --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_execution_report.c @@ -0,0 +1,724 @@ +#include +#include +#include +#include "order_execution_report.h" + + +char* sideorder_execution_report_ToString(ems___rest_api_order_execution_report__e side) { + char* sideArray[] = { "NULL", "BUY", "SELL" }; + return sideArray[side]; +} + +ems___rest_api_order_execution_report__e sideorder_execution_report_FromString(char* side){ + int stringToReturn = 0; + char *sideArray[] = { "NULL", "BUY", "SELL" }; + size_t sizeofArray = sizeof(sideArray) / sizeof(sideArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(side, sideArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* order_typeorder_execution_report_ToString(ems___rest_api_order_execution_report__e order_type) { + char* order_typeArray[] = { "NULL", "LIMIT" }; + return order_typeArray[order_type]; +} + +ems___rest_api_order_execution_report__e order_typeorder_execution_report_FromString(char* order_type){ + int stringToReturn = 0; + char *order_typeArray[] = { "NULL", "LIMIT" }; + size_t sizeofArray = sizeof(order_typeArray) / sizeof(order_typeArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(order_type, order_typeArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* time_in_forceorder_execution_report_ToString(ems___rest_api_order_execution_report__e time_in_force) { + char* time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + return time_in_forceArray[time_in_force]; +} + +ems___rest_api_order_execution_report__e time_in_forceorder_execution_report_FromString(char* time_in_force){ + int stringToReturn = 0; + char *time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + size_t sizeofArray = sizeof(time_in_forceArray) / sizeof(time_in_forceArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(time_in_force, time_in_forceArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* exec_instorder_execution_report_ToString(ems___rest_api_order_execution_report_EXECINST_e exec_inst) { + char *exec_instArray[] = { "NULL", "MAKER_OR_CANCEL", "AUCTION_ONLY", "INDICATION_OF_INTEREST" }; + return exec_instArray[exec_inst - 1]; +} + +ems___rest_api_order_execution_report_EXECINST_e exec_instorder_execution_report_FromString(char* exec_inst) { + int stringToReturn = 0; + char *exec_instArray[] = { "NULL", "MAKER_OR_CANCEL", "AUCTION_ONLY", "INDICATION_OF_INTEREST" }; + size_t sizeofArray = sizeof(exec_instArray) / sizeof(exec_instArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(exec_inst, exec_instArray[stringToReturn]) == 0) { + return stringToReturn + 1; + } + stringToReturn++; + } + return 0; +} +char* statusorder_execution_report_ToString(ems___rest_api_order_execution_report__e status) { + char* statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + return statusArray[status]; +} + +ems___rest_api_order_execution_report__e statusorder_execution_report_FromString(char* status){ + int stringToReturn = 0; + char *statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(status, statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +order_execution_report_t *order_execution_report_create( + char *exchange_id, + char *client_order_id, + char *symbol_id_exchange, + char *symbol_id_coinapi, + double amount_order, + double price, + ord_side_t *side, + ord_type_t *order_type, + time_in_force_t *time_in_force, + list_t *exec_inst, + char *client_order_id_format_exchange, + char *exchange_order_id, + double amount_open, + double amount_filled, + double avg_px, + ord_status_t *status, + list_t *status_history, + char *error_message, + list_t *fills + ) { + order_execution_report_t *order_execution_report_local_var = malloc(sizeof(order_execution_report_t)); + if (!order_execution_report_local_var) { + return NULL; + } + order_execution_report_local_var->exchange_id = exchange_id; + order_execution_report_local_var->client_order_id = client_order_id; + order_execution_report_local_var->symbol_id_exchange = symbol_id_exchange; + order_execution_report_local_var->symbol_id_coinapi = symbol_id_coinapi; + order_execution_report_local_var->amount_order = amount_order; + order_execution_report_local_var->price = price; + order_execution_report_local_var->side = side; + order_execution_report_local_var->order_type = order_type; + order_execution_report_local_var->time_in_force = time_in_force; + order_execution_report_local_var->expire_time = expire_time; + order_execution_report_local_var->exec_inst = exec_inst; + order_execution_report_local_var->client_order_id_format_exchange = client_order_id_format_exchange; + order_execution_report_local_var->exchange_order_id = exchange_order_id; + order_execution_report_local_var->amount_open = amount_open; + order_execution_report_local_var->amount_filled = amount_filled; + order_execution_report_local_var->avg_px = avg_px; + order_execution_report_local_var->status = status; + order_execution_report_local_var->status_history = status_history; + order_execution_report_local_var->error_message = error_message; + order_execution_report_local_var->fills = fills; + + return order_execution_report_local_var; +} + + +void order_execution_report_free(order_execution_report_t *order_execution_report) { + if(NULL == order_execution_report){ + return ; + } + listEntry_t *listEntry; + if (order_execution_report->exchange_id) { + free(order_execution_report->exchange_id); + order_execution_report->exchange_id = NULL; + } + if (order_execution_report->client_order_id) { + free(order_execution_report->client_order_id); + order_execution_report->client_order_id = NULL; + } + if (order_execution_report->symbol_id_exchange) { + free(order_execution_report->symbol_id_exchange); + order_execution_report->symbol_id_exchange = NULL; + } + if (order_execution_report->symbol_id_coinapi) { + free(order_execution_report->symbol_id_coinapi); + order_execution_report->symbol_id_coinapi = NULL; + } + if (order_execution_report->side) { + ord_side_free(order_execution_report->side); + order_execution_report->side = NULL; + } + if (order_execution_report->order_type) { + ord_type_free(order_execution_report->order_type); + order_execution_report->order_type = NULL; + } + if (order_execution_report->time_in_force) { + time_in_force_free(order_execution_report->time_in_force); + order_execution_report->time_in_force = NULL; + } + if (order_execution_report->exec_inst) { + list_ForEach(listEntry, order_execution_report->exec_inst) { + free(listEntry->data); + } + list_freeList(order_execution_report->exec_inst); + order_execution_report->exec_inst = NULL; + } + if (order_execution_report->client_order_id_format_exchange) { + free(order_execution_report->client_order_id_format_exchange); + order_execution_report->client_order_id_format_exchange = NULL; + } + if (order_execution_report->exchange_order_id) { + free(order_execution_report->exchange_order_id); + order_execution_report->exchange_order_id = NULL; + } + if (order_execution_report->status) { + ord_status_free(order_execution_report->status); + order_execution_report->status = NULL; + } + if (order_execution_report->status_history) { + list_ForEach(listEntry, order_execution_report->status_history) { + free(listEntry->data); + } + list_freeList(order_execution_report->status_history); + order_execution_report->status_history = NULL; + } + if (order_execution_report->error_message) { + free(order_execution_report->error_message); + order_execution_report->error_message = NULL; + } + if (order_execution_report->fills) { + list_ForEach(listEntry, order_execution_report->fills) { + fills_free(listEntry->data); + } + list_freeList(order_execution_report->fills); + order_execution_report->fills = NULL; + } + free(order_execution_report); +} + +cJSON *order_execution_report_convertToJSON(order_execution_report_t *order_execution_report) { + cJSON *item = cJSON_CreateObject(); + + // order_execution_report->exchange_id + if (!order_execution_report->exchange_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "exchange_id", order_execution_report->exchange_id) == NULL) { + goto fail; //String + } + + + // order_execution_report->client_order_id + if (!order_execution_report->client_order_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "client_order_id", order_execution_report->client_order_id) == NULL) { + goto fail; //String + } + + + // order_execution_report->symbol_id_exchange + if(order_execution_report->symbol_id_exchange) { + if(cJSON_AddStringToObject(item, "symbol_id_exchange", order_execution_report->symbol_id_exchange) == NULL) { + goto fail; //String + } + } + + + // order_execution_report->symbol_id_coinapi + if(order_execution_report->symbol_id_coinapi) { + if(cJSON_AddStringToObject(item, "symbol_id_coinapi", order_execution_report->symbol_id_coinapi) == NULL) { + goto fail; //String + } + } + + + // order_execution_report->amount_order + if (!order_execution_report->amount_order) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_order", order_execution_report->amount_order) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report->price + if (!order_execution_report->price) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "price", order_execution_report->price) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report->side + + cJSON *side_local_JSON = ord_side_convertToJSON(order_execution_report->side); + if(side_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "side", side_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_execution_report->order_type + + cJSON *order_type_local_JSON = ord_type_convertToJSON(order_execution_report->order_type); + if(order_type_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "order_type", order_type_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_execution_report->time_in_force + + cJSON *time_in_force_local_JSON = time_in_force_convertToJSON(order_execution_report->time_in_force); + if(time_in_force_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "time_in_force", time_in_force_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_execution_report->expire_time + if(order_execution_report->expire_time) { + } + + + // order_execution_report->exec_inst + + cJSON *exec_inst = cJSON_AddArrayToObject(item, "exec_inst"); + if(exec_inst == NULL) { + goto fail; //primitive container + } + + listEntry_t *exec_instListEntry; + list_ForEach(exec_instListEntry, order_execution_report->exec_inst) { + if(cJSON_AddStringToObject(exec_inst, "", (char*)exec_instListEntry->data) == NULL) + { + goto fail; + } + } + + + + // order_execution_report->client_order_id_format_exchange + if (!order_execution_report->client_order_id_format_exchange) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "client_order_id_format_exchange", order_execution_report->client_order_id_format_exchange) == NULL) { + goto fail; //String + } + + + // order_execution_report->exchange_order_id + if(order_execution_report->exchange_order_id) { + if(cJSON_AddStringToObject(item, "exchange_order_id", order_execution_report->exchange_order_id) == NULL) { + goto fail; //String + } + } + + + // order_execution_report->amount_open + if (!order_execution_report->amount_open) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_open", order_execution_report->amount_open) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report->amount_filled + if (!order_execution_report->amount_filled) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_filled", order_execution_report->amount_filled) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report->avg_px + if(order_execution_report->avg_px) { + if(cJSON_AddNumberToObject(item, "avg_px", order_execution_report->avg_px) == NULL) { + goto fail; //Numeric + } + } + + + // order_execution_report->status + + cJSON *status_local_JSON = ord_status_convertToJSON(order_execution_report->status); + if(status_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "status", status_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_execution_report->status_history + if(order_execution_report->status_history) { + cJSON *status_history = cJSON_AddArrayToObject(item, "status_history"); + if(status_history == NULL) { + goto fail; //primitive container + } + + listEntry_t *status_historyListEntry; + list_ForEach(status_historyListEntry, order_execution_report->status_history) { + } + } + + + // order_execution_report->error_message + if(order_execution_report->error_message) { + if(cJSON_AddStringToObject(item, "error_message", order_execution_report->error_message) == NULL) { + goto fail; //String + } + } + + + // order_execution_report->fills + if(order_execution_report->fills) { + cJSON *fills = cJSON_AddArrayToObject(item, "fills"); + if(fills == NULL) { + goto fail; //nonprimitive container + } + + listEntry_t *fillsListEntry; + if (order_execution_report->fills) { + list_ForEach(fillsListEntry, order_execution_report->fills) { + cJSON *itemLocal = fills_convertToJSON(fillsListEntry->data); + if(itemLocal == NULL) { + goto fail; + } + cJSON_AddItemToArray(fills, itemLocal); + } + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_execution_report_t *order_execution_report_parseFromJSON(cJSON *order_execution_reportJSON){ + + order_execution_report_t *order_execution_report_local_var = NULL; + + // define the local variable for order_execution_report->side + ord_side_t *side_local_nonprim = NULL; + + // define the local variable for order_execution_report->order_type + ord_type_t *order_type_local_nonprim = NULL; + + // define the local variable for order_execution_report->time_in_force + time_in_force_t *time_in_force_local_nonprim = NULL; + + // define the local variable for order_execution_report->status + ord_status_t *status_local_nonprim = NULL; + + // order_execution_report->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "exchange_id"); + if (!exchange_id) { + goto end; + } + + + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + + // order_execution_report->client_order_id + cJSON *client_order_id = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "client_order_id"); + if (!client_order_id) { + goto end; + } + + + if(!cJSON_IsString(client_order_id)) + { + goto end; //String + } + + // order_execution_report->symbol_id_exchange + cJSON *symbol_id_exchange = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "symbol_id_exchange"); + if (symbol_id_exchange) { + if(!cJSON_IsString(symbol_id_exchange)) + { + goto end; //String + } + } + + // order_execution_report->symbol_id_coinapi + cJSON *symbol_id_coinapi = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "symbol_id_coinapi"); + if (symbol_id_coinapi) { + if(!cJSON_IsString(symbol_id_coinapi)) + { + goto end; //String + } + } + + // order_execution_report->amount_order + cJSON *amount_order = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "amount_order"); + if (!amount_order) { + goto end; + } + + + if(!cJSON_IsNumber(amount_order)) + { + goto end; //Numeric + } + + // order_execution_report->price + cJSON *price = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "price"); + if (!price) { + goto end; + } + + + if(!cJSON_IsNumber(price)) + { + goto end; //Numeric + } + + // order_execution_report->side + cJSON *side = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "side"); + if (!side) { + goto end; + } + + + side_local_nonprim = ord_side_parseFromJSON(side); //custom + + // order_execution_report->order_type + cJSON *order_type = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "order_type"); + if (!order_type) { + goto end; + } + + + order_type_local_nonprim = ord_type_parseFromJSON(order_type); //custom + + // order_execution_report->time_in_force + cJSON *time_in_force = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "time_in_force"); + if (!time_in_force) { + goto end; + } + + + time_in_force_local_nonprim = time_in_force_parseFromJSON(time_in_force); //custom + + // order_execution_report->expire_time + cJSON *expire_time = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "expire_time"); + } + + // order_execution_report->exec_inst + cJSON *exec_inst = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "exec_inst"); + list_t *exec_instList; + if (exec_inst) { + cJSON *exec_inst_local; + if(!cJSON_IsArray(exec_inst)) { + goto end;//primitive container + } + exec_instList = list_createList(); + + cJSON_ArrayForEach(exec_inst_local, exec_inst) + { + if(!cJSON_IsString(exec_inst_local)) + { + goto end; + } + list_addElement(exec_instList , strdup(exec_inst_local->valuestring)); + } + } + + // order_execution_report->client_order_id_format_exchange + cJSON *client_order_id_format_exchange = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "client_order_id_format_exchange"); + if (!client_order_id_format_exchange) { + goto end; + } + + + if(!cJSON_IsString(client_order_id_format_exchange)) + { + goto end; //String + } + + // order_execution_report->exchange_order_id + cJSON *exchange_order_id = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "exchange_order_id"); + if (exchange_order_id) { + if(!cJSON_IsString(exchange_order_id)) + { + goto end; //String + } + } + + // order_execution_report->amount_open + cJSON *amount_open = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "amount_open"); + if (!amount_open) { + goto end; + } + + + if(!cJSON_IsNumber(amount_open)) + { + goto end; //Numeric + } + + // order_execution_report->amount_filled + cJSON *amount_filled = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "amount_filled"); + if (!amount_filled) { + goto end; + } + + + if(!cJSON_IsNumber(amount_filled)) + { + goto end; //Numeric + } + + // order_execution_report->avg_px + cJSON *avg_px = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "avg_px"); + if (avg_px) { + if(!cJSON_IsNumber(avg_px)) + { + goto end; //Numeric + } + } + + // order_execution_report->status + cJSON *status = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "status"); + if (!status) { + goto end; + } + + + status_local_nonprim = ord_status_parseFromJSON(status); //custom + + // order_execution_report->status_history + cJSON *status_history = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "status_history"); + list_t *status_historyList; + if (status_history) { + cJSON *status_history_local; + if(!cJSON_IsArray(status_history)) { + goto end;//primitive container + } + status_historyList = list_createList(); + + cJSON_ArrayForEach(status_history_local, status_history) + { + } + } + + // order_execution_report->error_message + cJSON *error_message = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "error_message"); + if (error_message) { + if(!cJSON_IsString(error_message)) + { + goto end; //String + } + } + + // order_execution_report->fills + cJSON *fills = cJSON_GetObjectItemCaseSensitive(order_execution_reportJSON, "fills"); + list_t *fillsList; + if (fills) { + cJSON *fills_local_nonprimitive; + if(!cJSON_IsArray(fills)){ + goto end; //nonprimitive container + } + + fillsList = list_createList(); + + cJSON_ArrayForEach(fills_local_nonprimitive,fills ) + { + if(!cJSON_IsObject(fills_local_nonprimitive)){ + goto end; + } + fills_t *fillsItem = fills_parseFromJSON(fills_local_nonprimitive); + + list_addElement(fillsList, fillsItem); + } + } + + + order_execution_report_local_var = order_execution_report_create ( + strdup(exchange_id->valuestring), + strdup(client_order_id->valuestring), + symbol_id_exchange ? strdup(symbol_id_exchange->valuestring) : NULL, + symbol_id_coinapi ? strdup(symbol_id_coinapi->valuestring) : NULL, + amount_order->valuedouble, + price->valuedouble, + side_local_nonprim, + order_type_local_nonprim, + time_in_force_local_nonprim, + exec_inst ? exec_instList : NULL, + strdup(client_order_id_format_exchange->valuestring), + exchange_order_id ? strdup(exchange_order_id->valuestring) : NULL, + amount_open->valuedouble, + amount_filled->valuedouble, + avg_px ? avg_px->valuedouble : 0, + status_local_nonprim, + status_history ? status_historyList : NULL, + error_message ? strdup(error_message->valuestring) : NULL, + fills ? fillsList : NULL + ); + + return order_execution_report_local_var; +end: + if (side_local_nonprim) { + ord_side_free(side_local_nonprim); + side_local_nonprim = NULL; + } + if (order_type_local_nonprim) { + ord_type_free(order_type_local_nonprim); + order_type_local_nonprim = NULL; + } + if (time_in_force_local_nonprim) { + time_in_force_free(time_in_force_local_nonprim); + time_in_force_local_nonprim = NULL; + } + if (status_local_nonprim) { + ord_status_free(status_local_nonprim); + status_local_nonprim = NULL; + } + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/order_execution_report.h b/ems-cloud-mgmt-sdk/c/model/order_execution_report.h new file mode 100644 index 0000000000..b39396e2f4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_execution_report.h @@ -0,0 +1,120 @@ +/* + * order_execution_report.h + * + * The order execution report object. + */ + +#ifndef _order_execution_report_H_ +#define _order_execution_report_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct order_execution_report_t order_execution_report_t; + +#include "fills.h" +#include "ord_side.h" +#include "ord_status.h" +#include "ord_type.h" +#include "order_execution_report_all_of.h" +#include "order_new_single_request.h" +#include "time_in_force.h" + +// Enum for order_execution_report + +typedef enum { ems___rest_api_order_execution_report__NULL = 0, ems___rest_api_order_execution_report__BUY, ems___rest_api_order_execution_report__SELL } ems___rest_api_order_execution_report__e; + +char* order_execution_report_side_ToString(ems___rest_api_order_execution_report__e side); + +ems___rest_api_order_execution_report__e order_execution_report_side_FromString(char* side); + +// Enum for order_execution_report + +typedef enum { ems___rest_api_order_execution_report__NULL = 0, ems___rest_api_order_execution_report__LIMIT } ems___rest_api_order_execution_report__e; + +char* order_execution_report_order_type_ToString(ems___rest_api_order_execution_report__e order_type); + +ems___rest_api_order_execution_report__e order_execution_report_order_type_FromString(char* order_type); + +// Enum for order_execution_report + +typedef enum { ems___rest_api_order_execution_report__NULL = 0, ems___rest_api_order_execution_report__GOOD_TILL_CANCEL, ems___rest_api_order_execution_report__GOOD_TILL_TIME_EXCHANGE, ems___rest_api_order_execution_report__GOOD_TILL_TIME_OMS, ems___rest_api_order_execution_report__FILL_OR_KILL, ems___rest_api_order_execution_report__IMMEDIATE_OR_CANCEL } ems___rest_api_order_execution_report__e; + +char* order_execution_report_time_in_force_ToString(ems___rest_api_order_execution_report__e time_in_force); + +ems___rest_api_order_execution_report__e order_execution_report_time_in_force_FromString(char* time_in_force); + +// Enum EXECINST for order_execution_report + +typedef enum { ems___rest_api_order_execution_report_EXECINST_NULL = 0, ems___rest_api_order_execution_report_EXECINST_MAKER_OR_CANCEL, ems___rest_api_order_execution_report_EXECINST_AUCTION_ONLY, ems___rest_api_order_execution_report_EXECINST_INDICATION_OF_INTEREST } ems___rest_api_order_execution_report_EXECINST_e; + +char* order_execution_report_exec_inst_ToString(ems___rest_api_order_execution_report_EXECINST_e exec_inst); + +ems___rest_api_order_execution_report_EXECINST_e order_execution_report_exec_inst_FromString(char* exec_inst); + +// Enum for order_execution_report + +typedef enum { ems___rest_api_order_execution_report__NULL = 0, ems___rest_api_order_execution_report__RECEIVED, ems___rest_api_order_execution_report__ROUTING, ems___rest_api_order_execution_report__ROUTED, ems___rest_api_order_execution_report___NEW, ems___rest_api_order_execution_report__PENDING_CANCEL, ems___rest_api_order_execution_report__PARTIALLY_FILLED, ems___rest_api_order_execution_report__FILLED, ems___rest_api_order_execution_report__CANCELED, ems___rest_api_order_execution_report__REJECTED } ems___rest_api_order_execution_report__e; + +char* order_execution_report_status_ToString(ems___rest_api_order_execution_report__e status); + +ems___rest_api_order_execution_report__e order_execution_report_status_FromString(char* status); + + + +typedef struct order_execution_report_t { + char *exchange_id; // string + char *client_order_id; // string + char *symbol_id_exchange; // string + char *symbol_id_coinapi; // string + double amount_order; //numeric + double price; //numeric + ord_side_t *side; // custom + ord_type_t *order_type; // custom + time_in_force_t *time_in_force; // custom + list_t *exec_inst; //primitive container + char *client_order_id_format_exchange; // string + char *exchange_order_id; // string + double amount_open; //numeric + double amount_filled; //numeric + double avg_px; //numeric + ord_status_t *status; // custom + list_t *status_history; //primitive container + char *error_message; // string + list_t *fills; //nonprimitive container + +} order_execution_report_t; + +order_execution_report_t *order_execution_report_create( + char *exchange_id, + char *client_order_id, + char *symbol_id_exchange, + char *symbol_id_coinapi, + double amount_order, + double price, + ord_side_t *side, + ord_type_t *order_type, + time_in_force_t *time_in_force, + list_t *exec_inst, + char *client_order_id_format_exchange, + char *exchange_order_id, + double amount_open, + double amount_filled, + double avg_px, + ord_status_t *status, + list_t *status_history, + char *error_message, + list_t *fills +); + +void order_execution_report_free(order_execution_report_t *order_execution_report); + +order_execution_report_t *order_execution_report_parseFromJSON(cJSON *order_execution_reportJSON); + +cJSON *order_execution_report_convertToJSON(order_execution_report_t *order_execution_report); + +#endif /* _order_execution_report_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.c b/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.c new file mode 100644 index 0000000000..31f892c97b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.c @@ -0,0 +1,338 @@ +#include +#include +#include +#include "order_execution_report_all_of.h" + + +char* statusorder_execution_report_all_of_ToString(ems___rest_api_order_execution_report_all_of__e status) { + char* statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + return statusArray[status]; +} + +ems___rest_api_order_execution_report_all_of__e statusorder_execution_report_all_of_FromString(char* status){ + int stringToReturn = 0; + char *statusArray[] = { "NULL", "RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" }; + size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(status, statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +order_execution_report_all_of_t *order_execution_report_all_of_create( + char *client_order_id_format_exchange, + char *exchange_order_id, + double amount_open, + double amount_filled, + double avg_px, + ord_status_t *status, + list_t *status_history, + char *error_message, + list_t *fills + ) { + order_execution_report_all_of_t *order_execution_report_all_of_local_var = malloc(sizeof(order_execution_report_all_of_t)); + if (!order_execution_report_all_of_local_var) { + return NULL; + } + order_execution_report_all_of_local_var->client_order_id_format_exchange = client_order_id_format_exchange; + order_execution_report_all_of_local_var->exchange_order_id = exchange_order_id; + order_execution_report_all_of_local_var->amount_open = amount_open; + order_execution_report_all_of_local_var->amount_filled = amount_filled; + order_execution_report_all_of_local_var->avg_px = avg_px; + order_execution_report_all_of_local_var->status = status; + order_execution_report_all_of_local_var->status_history = status_history; + order_execution_report_all_of_local_var->error_message = error_message; + order_execution_report_all_of_local_var->fills = fills; + + return order_execution_report_all_of_local_var; +} + + +void order_execution_report_all_of_free(order_execution_report_all_of_t *order_execution_report_all_of) { + if(NULL == order_execution_report_all_of){ + return ; + } + listEntry_t *listEntry; + if (order_execution_report_all_of->client_order_id_format_exchange) { + free(order_execution_report_all_of->client_order_id_format_exchange); + order_execution_report_all_of->client_order_id_format_exchange = NULL; + } + if (order_execution_report_all_of->exchange_order_id) { + free(order_execution_report_all_of->exchange_order_id); + order_execution_report_all_of->exchange_order_id = NULL; + } + if (order_execution_report_all_of->status) { + ord_status_free(order_execution_report_all_of->status); + order_execution_report_all_of->status = NULL; + } + if (order_execution_report_all_of->status_history) { + list_ForEach(listEntry, order_execution_report_all_of->status_history) { + free(listEntry->data); + } + list_freeList(order_execution_report_all_of->status_history); + order_execution_report_all_of->status_history = NULL; + } + if (order_execution_report_all_of->error_message) { + free(order_execution_report_all_of->error_message); + order_execution_report_all_of->error_message = NULL; + } + if (order_execution_report_all_of->fills) { + list_ForEach(listEntry, order_execution_report_all_of->fills) { + fills_free(listEntry->data); + } + list_freeList(order_execution_report_all_of->fills); + order_execution_report_all_of->fills = NULL; + } + free(order_execution_report_all_of); +} + +cJSON *order_execution_report_all_of_convertToJSON(order_execution_report_all_of_t *order_execution_report_all_of) { + cJSON *item = cJSON_CreateObject(); + + // order_execution_report_all_of->client_order_id_format_exchange + if (!order_execution_report_all_of->client_order_id_format_exchange) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "client_order_id_format_exchange", order_execution_report_all_of->client_order_id_format_exchange) == NULL) { + goto fail; //String + } + + + // order_execution_report_all_of->exchange_order_id + if(order_execution_report_all_of->exchange_order_id) { + if(cJSON_AddStringToObject(item, "exchange_order_id", order_execution_report_all_of->exchange_order_id) == NULL) { + goto fail; //String + } + } + + + // order_execution_report_all_of->amount_open + if (!order_execution_report_all_of->amount_open) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_open", order_execution_report_all_of->amount_open) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report_all_of->amount_filled + if (!order_execution_report_all_of->amount_filled) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_filled", order_execution_report_all_of->amount_filled) == NULL) { + goto fail; //Numeric + } + + + // order_execution_report_all_of->avg_px + if(order_execution_report_all_of->avg_px) { + if(cJSON_AddNumberToObject(item, "avg_px", order_execution_report_all_of->avg_px) == NULL) { + goto fail; //Numeric + } + } + + + // order_execution_report_all_of->status + + cJSON *status_local_JSON = ord_status_convertToJSON(order_execution_report_all_of->status); + if(status_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "status", status_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_execution_report_all_of->status_history + if(order_execution_report_all_of->status_history) { + cJSON *status_history = cJSON_AddArrayToObject(item, "status_history"); + if(status_history == NULL) { + goto fail; //primitive container + } + + listEntry_t *status_historyListEntry; + list_ForEach(status_historyListEntry, order_execution_report_all_of->status_history) { + } + } + + + // order_execution_report_all_of->error_message + if(order_execution_report_all_of->error_message) { + if(cJSON_AddStringToObject(item, "error_message", order_execution_report_all_of->error_message) == NULL) { + goto fail; //String + } + } + + + // order_execution_report_all_of->fills + if(order_execution_report_all_of->fills) { + cJSON *fills = cJSON_AddArrayToObject(item, "fills"); + if(fills == NULL) { + goto fail; //nonprimitive container + } + + listEntry_t *fillsListEntry; + if (order_execution_report_all_of->fills) { + list_ForEach(fillsListEntry, order_execution_report_all_of->fills) { + cJSON *itemLocal = fills_convertToJSON(fillsListEntry->data); + if(itemLocal == NULL) { + goto fail; + } + cJSON_AddItemToArray(fills, itemLocal); + } + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_execution_report_all_of_t *order_execution_report_all_of_parseFromJSON(cJSON *order_execution_report_all_ofJSON){ + + order_execution_report_all_of_t *order_execution_report_all_of_local_var = NULL; + + // define the local variable for order_execution_report_all_of->status + ord_status_t *status_local_nonprim = NULL; + + // order_execution_report_all_of->client_order_id_format_exchange + cJSON *client_order_id_format_exchange = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "client_order_id_format_exchange"); + if (!client_order_id_format_exchange) { + goto end; + } + + + if(!cJSON_IsString(client_order_id_format_exchange)) + { + goto end; //String + } + + // order_execution_report_all_of->exchange_order_id + cJSON *exchange_order_id = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "exchange_order_id"); + if (exchange_order_id) { + if(!cJSON_IsString(exchange_order_id)) + { + goto end; //String + } + } + + // order_execution_report_all_of->amount_open + cJSON *amount_open = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "amount_open"); + if (!amount_open) { + goto end; + } + + + if(!cJSON_IsNumber(amount_open)) + { + goto end; //Numeric + } + + // order_execution_report_all_of->amount_filled + cJSON *amount_filled = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "amount_filled"); + if (!amount_filled) { + goto end; + } + + + if(!cJSON_IsNumber(amount_filled)) + { + goto end; //Numeric + } + + // order_execution_report_all_of->avg_px + cJSON *avg_px = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "avg_px"); + if (avg_px) { + if(!cJSON_IsNumber(avg_px)) + { + goto end; //Numeric + } + } + + // order_execution_report_all_of->status + cJSON *status = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "status"); + if (!status) { + goto end; + } + + + status_local_nonprim = ord_status_parseFromJSON(status); //custom + + // order_execution_report_all_of->status_history + cJSON *status_history = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "status_history"); + list_t *status_historyList; + if (status_history) { + cJSON *status_history_local; + if(!cJSON_IsArray(status_history)) { + goto end;//primitive container + } + status_historyList = list_createList(); + + cJSON_ArrayForEach(status_history_local, status_history) + { + } + } + + // order_execution_report_all_of->error_message + cJSON *error_message = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "error_message"); + if (error_message) { + if(!cJSON_IsString(error_message)) + { + goto end; //String + } + } + + // order_execution_report_all_of->fills + cJSON *fills = cJSON_GetObjectItemCaseSensitive(order_execution_report_all_ofJSON, "fills"); + list_t *fillsList; + if (fills) { + cJSON *fills_local_nonprimitive; + if(!cJSON_IsArray(fills)){ + goto end; //nonprimitive container + } + + fillsList = list_createList(); + + cJSON_ArrayForEach(fills_local_nonprimitive,fills ) + { + if(!cJSON_IsObject(fills_local_nonprimitive)){ + goto end; + } + fills_t *fillsItem = fills_parseFromJSON(fills_local_nonprimitive); + + list_addElement(fillsList, fillsItem); + } + } + + + order_execution_report_all_of_local_var = order_execution_report_all_of_create ( + strdup(client_order_id_format_exchange->valuestring), + exchange_order_id ? strdup(exchange_order_id->valuestring) : NULL, + amount_open->valuedouble, + amount_filled->valuedouble, + avg_px ? avg_px->valuedouble : 0, + status_local_nonprim, + status_history ? status_historyList : NULL, + error_message ? strdup(error_message->valuestring) : NULL, + fills ? fillsList : NULL + ); + + return order_execution_report_all_of_local_var; +end: + if (status_local_nonprim) { + ord_status_free(status_local_nonprim); + status_local_nonprim = NULL; + } + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.h b/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.h new file mode 100644 index 0000000000..a2d0998a33 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_execution_report_all_of.h @@ -0,0 +1,63 @@ +/* + * order_execution_report_all_of.h + * + * The order execution report message. + */ + +#ifndef _order_execution_report_all_of_H_ +#define _order_execution_report_all_of_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct order_execution_report_all_of_t order_execution_report_all_of_t; + +#include "fills.h" +#include "ord_status.h" + +// Enum for order_execution_report_all_of + +typedef enum { ems___rest_api_order_execution_report_all_of__NULL = 0, ems___rest_api_order_execution_report_all_of__RECEIVED, ems___rest_api_order_execution_report_all_of__ROUTING, ems___rest_api_order_execution_report_all_of__ROUTED, ems___rest_api_order_execution_report_all_of___NEW, ems___rest_api_order_execution_report_all_of__PENDING_CANCEL, ems___rest_api_order_execution_report_all_of__PARTIALLY_FILLED, ems___rest_api_order_execution_report_all_of__FILLED, ems___rest_api_order_execution_report_all_of__CANCELED, ems___rest_api_order_execution_report_all_of__REJECTED } ems___rest_api_order_execution_report_all_of__e; + +char* order_execution_report_all_of_status_ToString(ems___rest_api_order_execution_report_all_of__e status); + +ems___rest_api_order_execution_report_all_of__e order_execution_report_all_of_status_FromString(char* status); + + + +typedef struct order_execution_report_all_of_t { + char *client_order_id_format_exchange; // string + char *exchange_order_id; // string + double amount_open; //numeric + double amount_filled; //numeric + double avg_px; //numeric + ord_status_t *status; // custom + list_t *status_history; //primitive container + char *error_message; // string + list_t *fills; //nonprimitive container + +} order_execution_report_all_of_t; + +order_execution_report_all_of_t *order_execution_report_all_of_create( + char *client_order_id_format_exchange, + char *exchange_order_id, + double amount_open, + double amount_filled, + double avg_px, + ord_status_t *status, + list_t *status_history, + char *error_message, + list_t *fills +); + +void order_execution_report_all_of_free(order_execution_report_all_of_t *order_execution_report_all_of); + +order_execution_report_all_of_t *order_execution_report_all_of_parseFromJSON(cJSON *order_execution_report_all_ofJSON); + +cJSON *order_execution_report_all_of_convertToJSON(order_execution_report_all_of_t *order_execution_report_all_of); + +#endif /* _order_execution_report_all_of_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/order_new_single_request.c b/ems-cloud-mgmt-sdk/c/model/order_new_single_request.c new file mode 100644 index 0000000000..2c7287bbe2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_new_single_request.c @@ -0,0 +1,435 @@ +#include +#include +#include +#include "order_new_single_request.h" + + +char* sideorder_new_single_request_ToString(ems___rest_api_order_new_single_request__e side) { + char* sideArray[] = { "NULL", "BUY", "SELL" }; + return sideArray[side]; +} + +ems___rest_api_order_new_single_request__e sideorder_new_single_request_FromString(char* side){ + int stringToReturn = 0; + char *sideArray[] = { "NULL", "BUY", "SELL" }; + size_t sizeofArray = sizeof(sideArray) / sizeof(sideArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(side, sideArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* order_typeorder_new_single_request_ToString(ems___rest_api_order_new_single_request__e order_type) { + char* order_typeArray[] = { "NULL", "LIMIT" }; + return order_typeArray[order_type]; +} + +ems___rest_api_order_new_single_request__e order_typeorder_new_single_request_FromString(char* order_type){ + int stringToReturn = 0; + char *order_typeArray[] = { "NULL", "LIMIT" }; + size_t sizeofArray = sizeof(order_typeArray) / sizeof(order_typeArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(order_type, order_typeArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* time_in_forceorder_new_single_request_ToString(ems___rest_api_order_new_single_request__e time_in_force) { + char* time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + return time_in_forceArray[time_in_force]; +} + +ems___rest_api_order_new_single_request__e time_in_forceorder_new_single_request_FromString(char* time_in_force){ + int stringToReturn = 0; + char *time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + size_t sizeofArray = sizeof(time_in_forceArray) / sizeof(time_in_forceArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(time_in_force, time_in_forceArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} +char* exec_instorder_new_single_request_ToString(ems___rest_api_order_new_single_request_EXECINST_e exec_inst) { + char *exec_instArray[] = { "NULL", "MAKER_OR_CANCEL", "AUCTION_ONLY", "INDICATION_OF_INTEREST" }; + return exec_instArray[exec_inst - 1]; +} + +ems___rest_api_order_new_single_request_EXECINST_e exec_instorder_new_single_request_FromString(char* exec_inst) { + int stringToReturn = 0; + char *exec_instArray[] = { "NULL", "MAKER_OR_CANCEL", "AUCTION_ONLY", "INDICATION_OF_INTEREST" }; + size_t sizeofArray = sizeof(exec_instArray) / sizeof(exec_instArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(exec_inst, exec_instArray[stringToReturn]) == 0) { + return stringToReturn + 1; + } + stringToReturn++; + } + return 0; +} + +order_new_single_request_t *order_new_single_request_create( + char *exchange_id, + char *client_order_id, + char *symbol_id_exchange, + char *symbol_id_coinapi, + double amount_order, + double price, + ord_side_t *side, + ord_type_t *order_type, + time_in_force_t *time_in_force, + list_t *exec_inst + ) { + order_new_single_request_t *order_new_single_request_local_var = malloc(sizeof(order_new_single_request_t)); + if (!order_new_single_request_local_var) { + return NULL; + } + order_new_single_request_local_var->exchange_id = exchange_id; + order_new_single_request_local_var->client_order_id = client_order_id; + order_new_single_request_local_var->symbol_id_exchange = symbol_id_exchange; + order_new_single_request_local_var->symbol_id_coinapi = symbol_id_coinapi; + order_new_single_request_local_var->amount_order = amount_order; + order_new_single_request_local_var->price = price; + order_new_single_request_local_var->side = side; + order_new_single_request_local_var->order_type = order_type; + order_new_single_request_local_var->time_in_force = time_in_force; + order_new_single_request_local_var->expire_time = expire_time; + order_new_single_request_local_var->exec_inst = exec_inst; + + return order_new_single_request_local_var; +} + + +void order_new_single_request_free(order_new_single_request_t *order_new_single_request) { + if(NULL == order_new_single_request){ + return ; + } + listEntry_t *listEntry; + if (order_new_single_request->exchange_id) { + free(order_new_single_request->exchange_id); + order_new_single_request->exchange_id = NULL; + } + if (order_new_single_request->client_order_id) { + free(order_new_single_request->client_order_id); + order_new_single_request->client_order_id = NULL; + } + if (order_new_single_request->symbol_id_exchange) { + free(order_new_single_request->symbol_id_exchange); + order_new_single_request->symbol_id_exchange = NULL; + } + if (order_new_single_request->symbol_id_coinapi) { + free(order_new_single_request->symbol_id_coinapi); + order_new_single_request->symbol_id_coinapi = NULL; + } + if (order_new_single_request->side) { + ord_side_free(order_new_single_request->side); + order_new_single_request->side = NULL; + } + if (order_new_single_request->order_type) { + ord_type_free(order_new_single_request->order_type); + order_new_single_request->order_type = NULL; + } + if (order_new_single_request->time_in_force) { + time_in_force_free(order_new_single_request->time_in_force); + order_new_single_request->time_in_force = NULL; + } + if (order_new_single_request->exec_inst) { + list_ForEach(listEntry, order_new_single_request->exec_inst) { + free(listEntry->data); + } + list_freeList(order_new_single_request->exec_inst); + order_new_single_request->exec_inst = NULL; + } + free(order_new_single_request); +} + +cJSON *order_new_single_request_convertToJSON(order_new_single_request_t *order_new_single_request) { + cJSON *item = cJSON_CreateObject(); + + // order_new_single_request->exchange_id + if (!order_new_single_request->exchange_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "exchange_id", order_new_single_request->exchange_id) == NULL) { + goto fail; //String + } + + + // order_new_single_request->client_order_id + if (!order_new_single_request->client_order_id) { + goto fail; + } + + if(cJSON_AddStringToObject(item, "client_order_id", order_new_single_request->client_order_id) == NULL) { + goto fail; //String + } + + + // order_new_single_request->symbol_id_exchange + if(order_new_single_request->symbol_id_exchange) { + if(cJSON_AddStringToObject(item, "symbol_id_exchange", order_new_single_request->symbol_id_exchange) == NULL) { + goto fail; //String + } + } + + + // order_new_single_request->symbol_id_coinapi + if(order_new_single_request->symbol_id_coinapi) { + if(cJSON_AddStringToObject(item, "symbol_id_coinapi", order_new_single_request->symbol_id_coinapi) == NULL) { + goto fail; //String + } + } + + + // order_new_single_request->amount_order + if (!order_new_single_request->amount_order) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "amount_order", order_new_single_request->amount_order) == NULL) { + goto fail; //Numeric + } + + + // order_new_single_request->price + if (!order_new_single_request->price) { + goto fail; + } + + if(cJSON_AddNumberToObject(item, "price", order_new_single_request->price) == NULL) { + goto fail; //Numeric + } + + + // order_new_single_request->side + + cJSON *side_local_JSON = ord_side_convertToJSON(order_new_single_request->side); + if(side_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "side", side_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_new_single_request->order_type + + cJSON *order_type_local_JSON = ord_type_convertToJSON(order_new_single_request->order_type); + if(order_type_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "order_type", order_type_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_new_single_request->time_in_force + + cJSON *time_in_force_local_JSON = time_in_force_convertToJSON(order_new_single_request->time_in_force); + if(time_in_force_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "time_in_force", time_in_force_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + // order_new_single_request->expire_time + if(order_new_single_request->expire_time) { + } + + + // order_new_single_request->exec_inst + + cJSON *exec_inst = cJSON_AddArrayToObject(item, "exec_inst"); + if(exec_inst == NULL) { + goto fail; //primitive container + } + + listEntry_t *exec_instListEntry; + list_ForEach(exec_instListEntry, order_new_single_request->exec_inst) { + if(cJSON_AddStringToObject(exec_inst, "", (char*)exec_instListEntry->data) == NULL) + { + goto fail; + } + } + + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_new_single_request_t *order_new_single_request_parseFromJSON(cJSON *order_new_single_requestJSON){ + + order_new_single_request_t *order_new_single_request_local_var = NULL; + + // define the local variable for order_new_single_request->side + ord_side_t *side_local_nonprim = NULL; + + // define the local variable for order_new_single_request->order_type + ord_type_t *order_type_local_nonprim = NULL; + + // define the local variable for order_new_single_request->time_in_force + time_in_force_t *time_in_force_local_nonprim = NULL; + + // order_new_single_request->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "exchange_id"); + if (!exchange_id) { + goto end; + } + + + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + + // order_new_single_request->client_order_id + cJSON *client_order_id = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "client_order_id"); + if (!client_order_id) { + goto end; + } + + + if(!cJSON_IsString(client_order_id)) + { + goto end; //String + } + + // order_new_single_request->symbol_id_exchange + cJSON *symbol_id_exchange = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "symbol_id_exchange"); + if (symbol_id_exchange) { + if(!cJSON_IsString(symbol_id_exchange)) + { + goto end; //String + } + } + + // order_new_single_request->symbol_id_coinapi + cJSON *symbol_id_coinapi = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "symbol_id_coinapi"); + if (symbol_id_coinapi) { + if(!cJSON_IsString(symbol_id_coinapi)) + { + goto end; //String + } + } + + // order_new_single_request->amount_order + cJSON *amount_order = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "amount_order"); + if (!amount_order) { + goto end; + } + + + if(!cJSON_IsNumber(amount_order)) + { + goto end; //Numeric + } + + // order_new_single_request->price + cJSON *price = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "price"); + if (!price) { + goto end; + } + + + if(!cJSON_IsNumber(price)) + { + goto end; //Numeric + } + + // order_new_single_request->side + cJSON *side = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "side"); + if (!side) { + goto end; + } + + + side_local_nonprim = ord_side_parseFromJSON(side); //custom + + // order_new_single_request->order_type + cJSON *order_type = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "order_type"); + if (!order_type) { + goto end; + } + + + order_type_local_nonprim = ord_type_parseFromJSON(order_type); //custom + + // order_new_single_request->time_in_force + cJSON *time_in_force = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "time_in_force"); + if (!time_in_force) { + goto end; + } + + + time_in_force_local_nonprim = time_in_force_parseFromJSON(time_in_force); //custom + + // order_new_single_request->expire_time + cJSON *expire_time = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "expire_time"); + } + + // order_new_single_request->exec_inst + cJSON *exec_inst = cJSON_GetObjectItemCaseSensitive(order_new_single_requestJSON, "exec_inst"); + list_t *exec_instList; + if (exec_inst) { + cJSON *exec_inst_local; + if(!cJSON_IsArray(exec_inst)) { + goto end;//primitive container + } + exec_instList = list_createList(); + + cJSON_ArrayForEach(exec_inst_local, exec_inst) + { + if(!cJSON_IsString(exec_inst_local)) + { + goto end; + } + list_addElement(exec_instList , strdup(exec_inst_local->valuestring)); + } + } + + + order_new_single_request_local_var = order_new_single_request_create ( + strdup(exchange_id->valuestring), + strdup(client_order_id->valuestring), + symbol_id_exchange ? strdup(symbol_id_exchange->valuestring) : NULL, + symbol_id_coinapi ? strdup(symbol_id_coinapi->valuestring) : NULL, + amount_order->valuedouble, + price->valuedouble, + side_local_nonprim, + order_type_local_nonprim, + time_in_force_local_nonprim, + exec_inst ? exec_instList : NULL + ); + + return order_new_single_request_local_var; +end: + if (side_local_nonprim) { + ord_side_free(side_local_nonprim); + side_local_nonprim = NULL; + } + if (order_type_local_nonprim) { + ord_type_free(order_type_local_nonprim); + order_type_local_nonprim = NULL; + } + if (time_in_force_local_nonprim) { + time_in_force_free(time_in_force_local_nonprim); + time_in_force_local_nonprim = NULL; + } + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/order_new_single_request.h b/ems-cloud-mgmt-sdk/c/model/order_new_single_request.h new file mode 100644 index 0000000000..b157cb8da8 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/order_new_single_request.h @@ -0,0 +1,90 @@ +/* + * order_new_single_request.h + * + * The new order message. + */ + +#ifndef _order_new_single_request_H_ +#define _order_new_single_request_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct order_new_single_request_t order_new_single_request_t; + +#include "ord_side.h" +#include "ord_type.h" +#include "time_in_force.h" + +// Enum for order_new_single_request + +typedef enum { ems___rest_api_order_new_single_request__NULL = 0, ems___rest_api_order_new_single_request__BUY, ems___rest_api_order_new_single_request__SELL } ems___rest_api_order_new_single_request__e; + +char* order_new_single_request_side_ToString(ems___rest_api_order_new_single_request__e side); + +ems___rest_api_order_new_single_request__e order_new_single_request_side_FromString(char* side); + +// Enum for order_new_single_request + +typedef enum { ems___rest_api_order_new_single_request__NULL = 0, ems___rest_api_order_new_single_request__LIMIT } ems___rest_api_order_new_single_request__e; + +char* order_new_single_request_order_type_ToString(ems___rest_api_order_new_single_request__e order_type); + +ems___rest_api_order_new_single_request__e order_new_single_request_order_type_FromString(char* order_type); + +// Enum for order_new_single_request + +typedef enum { ems___rest_api_order_new_single_request__NULL = 0, ems___rest_api_order_new_single_request__GOOD_TILL_CANCEL, ems___rest_api_order_new_single_request__GOOD_TILL_TIME_EXCHANGE, ems___rest_api_order_new_single_request__GOOD_TILL_TIME_OMS, ems___rest_api_order_new_single_request__FILL_OR_KILL, ems___rest_api_order_new_single_request__IMMEDIATE_OR_CANCEL } ems___rest_api_order_new_single_request__e; + +char* order_new_single_request_time_in_force_ToString(ems___rest_api_order_new_single_request__e time_in_force); + +ems___rest_api_order_new_single_request__e order_new_single_request_time_in_force_FromString(char* time_in_force); + +// Enum EXECINST for order_new_single_request + +typedef enum { ems___rest_api_order_new_single_request_EXECINST_NULL = 0, ems___rest_api_order_new_single_request_EXECINST_MAKER_OR_CANCEL, ems___rest_api_order_new_single_request_EXECINST_AUCTION_ONLY, ems___rest_api_order_new_single_request_EXECINST_INDICATION_OF_INTEREST } ems___rest_api_order_new_single_request_EXECINST_e; + +char* order_new_single_request_exec_inst_ToString(ems___rest_api_order_new_single_request_EXECINST_e exec_inst); + +ems___rest_api_order_new_single_request_EXECINST_e order_new_single_request_exec_inst_FromString(char* exec_inst); + + + +typedef struct order_new_single_request_t { + char *exchange_id; // string + char *client_order_id; // string + char *symbol_id_exchange; // string + char *symbol_id_coinapi; // string + double amount_order; //numeric + double price; //numeric + ord_side_t *side; // custom + ord_type_t *order_type; // custom + time_in_force_t *time_in_force; // custom + list_t *exec_inst; //primitive container + +} order_new_single_request_t; + +order_new_single_request_t *order_new_single_request_create( + char *exchange_id, + char *client_order_id, + char *symbol_id_exchange, + char *symbol_id_coinapi, + double amount_order, + double price, + ord_side_t *side, + ord_type_t *order_type, + time_in_force_t *time_in_force, + list_t *exec_inst +); + +void order_new_single_request_free(order_new_single_request_t *order_new_single_request); + +order_new_single_request_t *order_new_single_request_parseFromJSON(cJSON *order_new_single_requestJSON); + +cJSON *order_new_single_request_convertToJSON(order_new_single_request_t *order_new_single_request); + +#endif /* _order_new_single_request_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/position.c b/ems-cloud-mgmt-sdk/c/model/position.c new file mode 100644 index 0000000000..90d9a7d197 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/position.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include "position.h" + + + +position_t *position_create( + char *exchange_id, + list_t *data + ) { + position_t *position_local_var = malloc(sizeof(position_t)); + if (!position_local_var) { + return NULL; + } + position_local_var->exchange_id = exchange_id; + position_local_var->data = data; + + return position_local_var; +} + + +void position_free(position_t *position) { + if(NULL == position){ + return ; + } + listEntry_t *listEntry; + if (position->exchange_id) { + free(position->exchange_id); + position->exchange_id = NULL; + } + if (position->data) { + list_ForEach(listEntry, position->data) { + position_data_free(listEntry->data); + } + list_freeList(position->data); + position->data = NULL; + } + free(position); +} + +cJSON *position_convertToJSON(position_t *position) { + cJSON *item = cJSON_CreateObject(); + + // position->exchange_id + if(position->exchange_id) { + if(cJSON_AddStringToObject(item, "exchange_id", position->exchange_id) == NULL) { + goto fail; //String + } + } + + + // position->data + if(position->data) { + cJSON *data = cJSON_AddArrayToObject(item, "data"); + if(data == NULL) { + goto fail; //nonprimitive container + } + + listEntry_t *dataListEntry; + if (position->data) { + list_ForEach(dataListEntry, position->data) { + cJSON *itemLocal = position_data_convertToJSON(dataListEntry->data); + if(itemLocal == NULL) { + goto fail; + } + cJSON_AddItemToArray(data, itemLocal); + } + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +position_t *position_parseFromJSON(cJSON *positionJSON){ + + position_t *position_local_var = NULL; + + // position->exchange_id + cJSON *exchange_id = cJSON_GetObjectItemCaseSensitive(positionJSON, "exchange_id"); + if (exchange_id) { + if(!cJSON_IsString(exchange_id)) + { + goto end; //String + } + } + + // position->data + cJSON *data = cJSON_GetObjectItemCaseSensitive(positionJSON, "data"); + list_t *dataList; + if (data) { + cJSON *data_local_nonprimitive; + if(!cJSON_IsArray(data)){ + goto end; //nonprimitive container + } + + dataList = list_createList(); + + cJSON_ArrayForEach(data_local_nonprimitive,data ) + { + if(!cJSON_IsObject(data_local_nonprimitive)){ + goto end; + } + position_data_t *dataItem = position_data_parseFromJSON(data_local_nonprimitive); + + list_addElement(dataList, dataItem); + } + } + + + position_local_var = position_create ( + exchange_id ? strdup(exchange_id->valuestring) : NULL, + data ? dataList : NULL + ); + + return position_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/position.h b/ems-cloud-mgmt-sdk/c/model/position.h new file mode 100644 index 0000000000..190c7b078b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/position.h @@ -0,0 +1,40 @@ +/* + * position.h + * + * + */ + +#ifndef _position_H_ +#define _position_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct position_t position_t; + +#include "position_data.h" + + + +typedef struct position_t { + char *exchange_id; // string + list_t *data; //nonprimitive container + +} position_t; + +position_t *position_create( + char *exchange_id, + list_t *data +); + +void position_free(position_t *position); + +position_t *position_parseFromJSON(cJSON *positionJSON); + +cJSON *position_convertToJSON(position_t *position); + +#endif /* _position_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/position_data.c b/ems-cloud-mgmt-sdk/c/model/position_data.c new file mode 100644 index 0000000000..186f1ca23a --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/position_data.c @@ -0,0 +1,294 @@ +#include +#include +#include +#include "position_data.h" + + +char* sideposition_data_ToString(ems___rest_api_position_data__e side) { + char* sideArray[] = { "NULL", "BUY", "SELL" }; + return sideArray[side]; +} + +ems___rest_api_position_data__e sideposition_data_FromString(char* side){ + int stringToReturn = 0; + char *sideArray[] = { "NULL", "BUY", "SELL" }; + size_t sizeofArray = sizeof(sideArray) / sizeof(sideArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(side, sideArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +position_data_t *position_data_create( + char *symbol_id_exchange, + char *symbol_id_coinapi, + double avg_entry_price, + double quantity, + ord_side_t *side, + double unrealized_pnl, + double leverage, + int cross_margin, + double liquidation_price, + object_t *raw_data + ) { + position_data_t *position_data_local_var = malloc(sizeof(position_data_t)); + if (!position_data_local_var) { + return NULL; + } + position_data_local_var->symbol_id_exchange = symbol_id_exchange; + position_data_local_var->symbol_id_coinapi = symbol_id_coinapi; + position_data_local_var->avg_entry_price = avg_entry_price; + position_data_local_var->quantity = quantity; + position_data_local_var->side = side; + position_data_local_var->unrealized_pnl = unrealized_pnl; + position_data_local_var->leverage = leverage; + position_data_local_var->cross_margin = cross_margin; + position_data_local_var->liquidation_price = liquidation_price; + position_data_local_var->raw_data = raw_data; + + return position_data_local_var; +} + + +void position_data_free(position_data_t *position_data) { + if(NULL == position_data){ + return ; + } + listEntry_t *listEntry; + if (position_data->symbol_id_exchange) { + free(position_data->symbol_id_exchange); + position_data->symbol_id_exchange = NULL; + } + if (position_data->symbol_id_coinapi) { + free(position_data->symbol_id_coinapi); + position_data->symbol_id_coinapi = NULL; + } + if (position_data->side) { + ord_side_free(position_data->side); + position_data->side = NULL; + } + if (position_data->raw_data) { + object_free(position_data->raw_data); + position_data->raw_data = NULL; + } + free(position_data); +} + +cJSON *position_data_convertToJSON(position_data_t *position_data) { + cJSON *item = cJSON_CreateObject(); + + // position_data->symbol_id_exchange + if(position_data->symbol_id_exchange) { + if(cJSON_AddStringToObject(item, "symbol_id_exchange", position_data->symbol_id_exchange) == NULL) { + goto fail; //String + } + } + + + // position_data->symbol_id_coinapi + if(position_data->symbol_id_coinapi) { + if(cJSON_AddStringToObject(item, "symbol_id_coinapi", position_data->symbol_id_coinapi) == NULL) { + goto fail; //String + } + } + + + // position_data->avg_entry_price + if(position_data->avg_entry_price) { + if(cJSON_AddNumberToObject(item, "avg_entry_price", position_data->avg_entry_price) == NULL) { + goto fail; //Numeric + } + } + + + // position_data->quantity + if(position_data->quantity) { + if(cJSON_AddNumberToObject(item, "quantity", position_data->quantity) == NULL) { + goto fail; //Numeric + } + } + + + // position_data->side + + cJSON *side_local_JSON = ord_side_convertToJSON(position_data->side); + if(side_local_JSON == NULL) { + goto fail; // custom + } + cJSON_AddItemToObject(item, "side", side_local_JSON); + if(item->child == NULL) { + goto fail; + } + + + + // position_data->unrealized_pnl + if(position_data->unrealized_pnl) { + if(cJSON_AddNumberToObject(item, "unrealized_pnl", position_data->unrealized_pnl) == NULL) { + goto fail; //Numeric + } + } + + + // position_data->leverage + if(position_data->leverage) { + if(cJSON_AddNumberToObject(item, "leverage", position_data->leverage) == NULL) { + goto fail; //Numeric + } + } + + + // position_data->cross_margin + if(position_data->cross_margin) { + if(cJSON_AddBoolToObject(item, "cross_margin", position_data->cross_margin) == NULL) { + goto fail; //Bool + } + } + + + // position_data->liquidation_price + if(position_data->liquidation_price) { + if(cJSON_AddNumberToObject(item, "liquidation_price", position_data->liquidation_price) == NULL) { + goto fail; //Numeric + } + } + + + // position_data->raw_data + if(position_data->raw_data) { + cJSON *raw_data_object = object_convertToJSON(position_data->raw_data); + if(raw_data_object == NULL) { + goto fail; //model + } + cJSON_AddItemToObject(item, "raw_data", raw_data_object); + if(item->child == NULL) { + goto fail; + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +position_data_t *position_data_parseFromJSON(cJSON *position_dataJSON){ + + position_data_t *position_data_local_var = NULL; + + // define the local variable for position_data->side + ord_side_t *side_local_nonprim = NULL; + + // position_data->symbol_id_exchange + cJSON *symbol_id_exchange = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "symbol_id_exchange"); + if (symbol_id_exchange) { + if(!cJSON_IsString(symbol_id_exchange)) + { + goto end; //String + } + } + + // position_data->symbol_id_coinapi + cJSON *symbol_id_coinapi = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "symbol_id_coinapi"); + if (symbol_id_coinapi) { + if(!cJSON_IsString(symbol_id_coinapi)) + { + goto end; //String + } + } + + // position_data->avg_entry_price + cJSON *avg_entry_price = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "avg_entry_price"); + if (avg_entry_price) { + if(!cJSON_IsNumber(avg_entry_price)) + { + goto end; //Numeric + } + } + + // position_data->quantity + cJSON *quantity = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "quantity"); + if (quantity) { + if(!cJSON_IsNumber(quantity)) + { + goto end; //Numeric + } + } + + // position_data->side + cJSON *side = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "side"); + if (side) { + side_local_nonprim = ord_side_parseFromJSON(side); //custom + } + + // position_data->unrealized_pnl + cJSON *unrealized_pnl = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "unrealized_pnl"); + if (unrealized_pnl) { + if(!cJSON_IsNumber(unrealized_pnl)) + { + goto end; //Numeric + } + } + + // position_data->leverage + cJSON *leverage = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "leverage"); + if (leverage) { + if(!cJSON_IsNumber(leverage)) + { + goto end; //Numeric + } + } + + // position_data->cross_margin + cJSON *cross_margin = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "cross_margin"); + if (cross_margin) { + if(!cJSON_IsBool(cross_margin)) + { + goto end; //Bool + } + } + + // position_data->liquidation_price + cJSON *liquidation_price = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "liquidation_price"); + if (liquidation_price) { + if(!cJSON_IsNumber(liquidation_price)) + { + goto end; //Numeric + } + } + + // position_data->raw_data + cJSON *raw_data = cJSON_GetObjectItemCaseSensitive(position_dataJSON, "raw_data"); + object_t *raw_data_local_object = NULL; + if (raw_data) { + raw_data_local_object = object_parseFromJSON(raw_data); //object + } + + + position_data_local_var = position_data_create ( + symbol_id_exchange ? strdup(symbol_id_exchange->valuestring) : NULL, + symbol_id_coinapi ? strdup(symbol_id_coinapi->valuestring) : NULL, + avg_entry_price ? avg_entry_price->valuedouble : 0, + quantity ? quantity->valuedouble : 0, + side ? side_local_nonprim : NULL, + unrealized_pnl ? unrealized_pnl->valuedouble : 0, + leverage ? leverage->valuedouble : 0, + cross_margin ? cross_margin->valueint : 0, + liquidation_price ? liquidation_price->valuedouble : 0, + raw_data ? raw_data_local_object : NULL + ); + + return position_data_local_var; +end: + if (side_local_nonprim) { + ord_side_free(side_local_nonprim); + side_local_nonprim = NULL; + } + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/position_data.h b/ems-cloud-mgmt-sdk/c/model/position_data.h new file mode 100644 index 0000000000..70ab802b63 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/position_data.h @@ -0,0 +1,65 @@ +/* + * position_data.h + * + * The Position object. + */ + +#ifndef _position_data_H_ +#define _position_data_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct position_data_t position_data_t; + +#include "object.h" +#include "ord_side.h" + +// Enum for position_data + +typedef enum { ems___rest_api_position_data__NULL = 0, ems___rest_api_position_data__BUY, ems___rest_api_position_data__SELL } ems___rest_api_position_data__e; + +char* position_data_side_ToString(ems___rest_api_position_data__e side); + +ems___rest_api_position_data__e position_data_side_FromString(char* side); + + + +typedef struct position_data_t { + char *symbol_id_exchange; // string + char *symbol_id_coinapi; // string + double avg_entry_price; //numeric + double quantity; //numeric + ord_side_t *side; // custom + double unrealized_pnl; //numeric + double leverage; //numeric + int cross_margin; //boolean + double liquidation_price; //numeric + object_t *raw_data; //object + +} position_data_t; + +position_data_t *position_data_create( + char *symbol_id_exchange, + char *symbol_id_coinapi, + double avg_entry_price, + double quantity, + ord_side_t *side, + double unrealized_pnl, + double leverage, + int cross_margin, + double liquidation_price, + object_t *raw_data +); + +void position_data_free(position_data_t *position_data); + +position_data_t *position_data_parseFromJSON(cJSON *position_dataJSON); + +cJSON *position_data_convertToJSON(position_data_t *position_data); + +#endif /* _position_data_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/reject_reason.c b/ems-cloud-mgmt-sdk/c/model/reject_reason.c new file mode 100644 index 0000000000..b6d5afd5f0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/reject_reason.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "reject_reason.h" + + +char* reject_reason_reject_reason_ToString(ems___rest_api_reject_reason__e reject_reason) { + char *reject_reasonArray[] = { "NULL", "OTHER", "EXCHANGE_UNREACHABLE", "EXCHANGE_RESPONSE_TIMEOUT", "ORDER_ID_NOT_FOUND", "INVALID_TYPE", "METHOD_NOT_SUPPORTED", "JSON_ERROR" }; + return reject_reasonArray[reject_reason]; +} + +ems___rest_api_reject_reason__e reject_reason_reject_reason_FromString(char* reject_reason) { + int stringToReturn = 0; + char *reject_reasonArray[] = { "NULL", "OTHER", "EXCHANGE_UNREACHABLE", "EXCHANGE_RESPONSE_TIMEOUT", "ORDER_ID_NOT_FOUND", "INVALID_TYPE", "METHOD_NOT_SUPPORTED", "JSON_ERROR" }; + size_t sizeofArray = sizeof(reject_reasonArray) / sizeof(reject_reasonArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(reject_reason, reject_reasonArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +cJSON *reject_reason_reject_reason_convertToJSON(ems___rest_api_reject_reason__e reject_reason) { + cJSON *item = cJSON_CreateObject(); + if(cJSON_AddStringToObject(item, "reject_reason", reject_reason_reject_reason_ToString(reject_reason)) == NULL) { + goto fail; + } + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +ems___rest_api_reject_reason__e reject_reason_reject_reason_parseFromJSON(cJSON *reject_reasonJSON) { + ems___rest_api_reject_reason__e *reject_reason = NULL; + ems___rest_api_reject_reason__e reject_reasonVariable; + cJSON *reject_reasonVar = cJSON_GetObjectItemCaseSensitive(reject_reasonJSON, "reject_reason"); + if(!cJSON_IsString(reject_reasonVar) || (reject_reasonVar->valuestring == NULL)){ + goto end; + } + reject_reasonVariable = reject_reason_reject_reason_FromString(reject_reasonVar->valuestring); + return reject_reasonVariable; +end: + return 0; +} diff --git a/ems-cloud-mgmt-sdk/c/model/reject_reason.h b/ems-cloud-mgmt-sdk/c/model/reject_reason.h new file mode 100644 index 0000000000..6c316c9389 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/reject_reason.h @@ -0,0 +1,32 @@ +/* + * reject_reason.h + * + * Cause of rejection. + */ + +#ifndef _reject_reason_H_ +#define _reject_reason_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct reject_reason_t reject_reason_t; + + +// Enum for reject_reason + +typedef enum { ems___rest_api_reject_reason__NULL = 0, ems___rest_api_reject_reason__OTHER, ems___rest_api_reject_reason__EXCHANGE_UNREACHABLE, ems___rest_api_reject_reason__EXCHANGE_RESPONSE_TIMEOUT, ems___rest_api_reject_reason__ORDER_ID_NOT_FOUND, ems___rest_api_reject_reason__INVALID_TYPE, ems___rest_api_reject_reason__METHOD_NOT_SUPPORTED, ems___rest_api_reject_reason__JSON_ERROR } ems___rest_api_reject_reason__e; + +char* reject_reason_reject_reason_ToString(ems___rest_api_reject_reason__e reject_reason); + +ems___rest_api_reject_reason__e reject_reason_reject_reason_FromString(char* reject_reason); + +//cJSON *reject_reason_reject_reason_convertToJSON(ems___rest_api_reject_reason__e reject_reason); + +//ems___rest_api_reject_reason__e reject_reason_reject_reason_parseFromJSON(cJSON *reject_reasonJSON); + +#endif /* _reject_reason_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/time_in_force.c b/ems-cloud-mgmt-sdk/c/model/time_in_force.c new file mode 100644 index 0000000000..e6282e1b2e --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/time_in_force.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include "time_in_force.h" + + +char* time_in_force_time_in_force_ToString(ems___rest_api_time_in_force__e time_in_force) { + char *time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + return time_in_forceArray[time_in_force]; +} + +ems___rest_api_time_in_force__e time_in_force_time_in_force_FromString(char* time_in_force) { + int stringToReturn = 0; + char *time_in_forceArray[] = { "NULL", "GOOD_TILL_CANCEL", "GOOD_TILL_TIME_EXCHANGE", "GOOD_TILL_TIME_OMS", "FILL_OR_KILL", "IMMEDIATE_OR_CANCEL" }; + size_t sizeofArray = sizeof(time_in_forceArray) / sizeof(time_in_forceArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(time_in_force, time_in_forceArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +cJSON *time_in_force_time_in_force_convertToJSON(ems___rest_api_time_in_force__e time_in_force) { + cJSON *item = cJSON_CreateObject(); + if(cJSON_AddStringToObject(item, "time_in_force", time_in_force_time_in_force_ToString(time_in_force)) == NULL) { + goto fail; + } + return item; +fail: + cJSON_Delete(item); + return NULL; +} + +ems___rest_api_time_in_force__e time_in_force_time_in_force_parseFromJSON(cJSON *time_in_forceJSON) { + ems___rest_api_time_in_force__e *time_in_force = NULL; + ems___rest_api_time_in_force__e time_in_forceVariable; + cJSON *time_in_forceVar = cJSON_GetObjectItemCaseSensitive(time_in_forceJSON, "time_in_force"); + if(!cJSON_IsString(time_in_forceVar) || (time_in_forceVar->valuestring == NULL)){ + goto end; + } + time_in_forceVariable = time_in_force_time_in_force_FromString(time_in_forceVar->valuestring); + return time_in_forceVariable; +end: + return 0; +} diff --git a/ems-cloud-mgmt-sdk/c/model/time_in_force.h b/ems-cloud-mgmt-sdk/c/model/time_in_force.h new file mode 100644 index 0000000000..bb6b02257c --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/time_in_force.h @@ -0,0 +1,32 @@ +/* + * time_in_force.h + * + * Order time in force options are documented in the separate section: <a href=\"#ems-order-params-tif\">EMS / Starter Guide / Order parameters / Time in force</a> + */ + +#ifndef _time_in_force_H_ +#define _time_in_force_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct time_in_force_t time_in_force_t; + + +// Enum for time_in_force + +typedef enum { ems___rest_api_time_in_force__NULL = 0, ems___rest_api_time_in_force__GOOD_TILL_CANCEL, ems___rest_api_time_in_force__GOOD_TILL_TIME_EXCHANGE, ems___rest_api_time_in_force__GOOD_TILL_TIME_OMS, ems___rest_api_time_in_force__FILL_OR_KILL, ems___rest_api_time_in_force__IMMEDIATE_OR_CANCEL } ems___rest_api_time_in_force__e; + +char* time_in_force_time_in_force_ToString(ems___rest_api_time_in_force__e time_in_force); + +ems___rest_api_time_in_force__e time_in_force_time_in_force_FromString(char* time_in_force); + +//cJSON *time_in_force_time_in_force_convertToJSON(ems___rest_api_time_in_force__e time_in_force); + +//ems___rest_api_time_in_force__e time_in_force_time_in_force_parseFromJSON(cJSON *time_in_forceJSON); + +#endif /* _time_in_force_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/model/validation_error.c b/ems-cloud-mgmt-sdk/c/model/validation_error.c new file mode 100644 index 0000000000..46a4a6b5bd --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/validation_error.c @@ -0,0 +1,165 @@ +#include +#include +#include +#include "validation_error.h" + + + +validation_error_t *validation_error_create( + char *type, + char *title, + double status, + char *trace_id, + char *errors + ) { + validation_error_t *validation_error_local_var = malloc(sizeof(validation_error_t)); + if (!validation_error_local_var) { + return NULL; + } + validation_error_local_var->type = type; + validation_error_local_var->title = title; + validation_error_local_var->status = status; + validation_error_local_var->trace_id = trace_id; + validation_error_local_var->errors = errors; + + return validation_error_local_var; +} + + +void validation_error_free(validation_error_t *validation_error) { + if(NULL == validation_error){ + return ; + } + listEntry_t *listEntry; + if (validation_error->type) { + free(validation_error->type); + validation_error->type = NULL; + } + if (validation_error->title) { + free(validation_error->title); + validation_error->title = NULL; + } + if (validation_error->trace_id) { + free(validation_error->trace_id); + validation_error->trace_id = NULL; + } + if (validation_error->errors) { + free(validation_error->errors); + validation_error->errors = NULL; + } + free(validation_error); +} + +cJSON *validation_error_convertToJSON(validation_error_t *validation_error) { + cJSON *item = cJSON_CreateObject(); + + // validation_error->type + if(validation_error->type) { + if(cJSON_AddStringToObject(item, "type", validation_error->type) == NULL) { + goto fail; //String + } + } + + + // validation_error->title + if(validation_error->title) { + if(cJSON_AddStringToObject(item, "title", validation_error->title) == NULL) { + goto fail; //String + } + } + + + // validation_error->status + if(validation_error->status) { + if(cJSON_AddNumberToObject(item, "status", validation_error->status) == NULL) { + goto fail; //Numeric + } + } + + + // validation_error->trace_id + if(validation_error->trace_id) { + if(cJSON_AddStringToObject(item, "traceId", validation_error->trace_id) == NULL) { + goto fail; //String + } + } + + + // validation_error->errors + if(validation_error->errors) { + if(cJSON_AddStringToObject(item, "errors", validation_error->errors) == NULL) { + goto fail; //String + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +validation_error_t *validation_error_parseFromJSON(cJSON *validation_errorJSON){ + + validation_error_t *validation_error_local_var = NULL; + + // validation_error->type + cJSON *type = cJSON_GetObjectItemCaseSensitive(validation_errorJSON, "type"); + if (type) { + if(!cJSON_IsString(type)) + { + goto end; //String + } + } + + // validation_error->title + cJSON *title = cJSON_GetObjectItemCaseSensitive(validation_errorJSON, "title"); + if (title) { + if(!cJSON_IsString(title)) + { + goto end; //String + } + } + + // validation_error->status + cJSON *status = cJSON_GetObjectItemCaseSensitive(validation_errorJSON, "status"); + if (status) { + if(!cJSON_IsNumber(status)) + { + goto end; //Numeric + } + } + + // validation_error->trace_id + cJSON *trace_id = cJSON_GetObjectItemCaseSensitive(validation_errorJSON, "traceId"); + if (trace_id) { + if(!cJSON_IsString(trace_id)) + { + goto end; //String + } + } + + // validation_error->errors + cJSON *errors = cJSON_GetObjectItemCaseSensitive(validation_errorJSON, "errors"); + if (errors) { + if(!cJSON_IsString(errors)) + { + goto end; //String + } + } + + + validation_error_local_var = validation_error_create ( + type ? strdup(type->valuestring) : NULL, + title ? strdup(title->valuestring) : NULL, + status ? status->valuedouble : 0, + trace_id ? strdup(trace_id->valuestring) : NULL, + errors ? strdup(errors->valuestring) : NULL + ); + + return validation_error_local_var; +end: + return NULL; + +} diff --git a/ems-cloud-mgmt-sdk/c/model/validation_error.h b/ems-cloud-mgmt-sdk/c/model/validation_error.h new file mode 100644 index 0000000000..84dc90aff1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/model/validation_error.h @@ -0,0 +1,45 @@ +/* + * validation_error.h + * + * + */ + +#ifndef _validation_error_H_ +#define _validation_error_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct validation_error_t validation_error_t; + + + + +typedef struct validation_error_t { + char *type; // string + char *title; // string + double status; //numeric + char *trace_id; // string + char *errors; // string + +} validation_error_t; + +validation_error_t *validation_error_create( + char *type, + char *title, + double status, + char *trace_id, + char *errors +); + +void validation_error_free(validation_error_t *validation_error); + +validation_error_t *validation_error_parseFromJSON(cJSON *validation_errorJSON); + +cJSON *validation_error_convertToJSON(validation_error_t *validation_error); + +#endif /* _validation_error_H_ */ + diff --git a/ems-cloud-mgmt-sdk/c/src/apiClient.c b/ems-cloud-mgmt-sdk/c/src/apiClient.c new file mode 100644 index 0000000000..9745cdd87b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/src/apiClient.c @@ -0,0 +1,492 @@ +#include +#include +#include +#include +#include "../include/apiClient.h" + +size_t writeDataCallback(void *buffer, size_t size, size_t nmemb, void *userp); + +apiClient_t *apiClient_create() { + apiClient_t *apiClient = malloc(sizeof(apiClient_t)); + apiClient->basePath = strdup("https://ems-gateway-aws-eu-central-1-dev.coinapi.io"); + apiClient->sslConfig = NULL; + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + apiClient->data_callback_func = NULL; + apiClient->progress_func = NULL; + apiClient->progress_data = NULL; + apiClient->response_code = 0; + + return apiClient; +} + +apiClient_t *apiClient_create_with_base_path(const char *basePath +, sslConfig_t *sslConfig +) { + apiClient_t *apiClient = malloc(sizeof(apiClient_t)); + if(basePath){ + apiClient->basePath = strdup(basePath); + }else{ + apiClient->basePath = strdup("https://ems-gateway-aws-eu-central-1-dev.coinapi.io"); + } + + if(sslConfig){ + apiClient->sslConfig = sslConfig; + }else{ + apiClient->sslConfig = NULL; + } + + apiClient->dataReceived = NULL; + apiClient->dataReceivedLen = 0; + apiClient->data_callback_func = NULL; + apiClient->progress_func = NULL; + apiClient->progress_data = NULL; + apiClient->response_code = 0; + + return apiClient; +} + +void apiClient_free(apiClient_t *apiClient) { + if(apiClient->basePath) { + free(apiClient->basePath); + } + apiClient->data_callback_func = NULL; + apiClient->progress_func = NULL; + apiClient->progress_data = NULL; + free(apiClient); +} + +sslConfig_t *sslConfig_create(const char *clientCertFile, const char *clientKeyFile, const char *CACertFile, int insecureSkipTlsVerify) { + sslConfig_t *sslConfig = calloc(1, sizeof(sslConfig_t)); + if ( clientCertFile ) { + sslConfig->clientCertFile = strdup(clientCertFile); + } + if ( clientKeyFile ) { + sslConfig->clientKeyFile = strdup(clientKeyFile); + } + if ( CACertFile ) { + sslConfig->CACertFile = strdup(CACertFile); + } + sslConfig->insecureSkipTlsVerify = insecureSkipTlsVerify; + return sslConfig; +} + +void sslConfig_free(sslConfig_t *sslConfig) { + if ( sslConfig->clientCertFile ) { + free(sslConfig->clientCertFile); + } + if ( sslConfig->clientKeyFile ) { + free(sslConfig->clientKeyFile); + } + if ( sslConfig->CACertFile ){ + free(sslConfig->CACertFile); + } + free(sslConfig); +} + +void replaceSpaceWithPlus(char *stringToProcess) { + for(int i = 0; i < strlen(stringToProcess); i++) { + if(stringToProcess[i] == ' ') { + stringToProcess[i] = '+'; + } + } +} + +char *assembleTargetUrl(char *basePath, + char *operationParameter, + list_t *queryParameters) { + int neededBufferSizeForQueryParameters = 0; + listEntry_t *listEntry; + + if(queryParameters != NULL) { + list_ForEach(listEntry, queryParameters) { + keyValuePair_t *pair = listEntry->data; + neededBufferSizeForQueryParameters += + strlen(pair->key) + strlen(pair->value); + } + + neededBufferSizeForQueryParameters += + (queryParameters->count * 2); // each keyValuePair is separated by a = and a & except the last, but this makes up for the ? at the beginning + } + + int operationParameterLength = 0; + int basePathLength = strlen(basePath); + + if(operationParameter != NULL) { + operationParameterLength = (1 + strlen(operationParameter)); + } + + char *targetUrl = + malloc( + neededBufferSizeForQueryParameters + basePathLength + operationParameterLength + + 1); + + strcpy(targetUrl, basePath); + + if(operationParameter != NULL) { + strcat(targetUrl, operationParameter); + } + + if(queryParameters != NULL) { + strcat(targetUrl, "?"); + list_ForEach(listEntry, queryParameters) { + keyValuePair_t *pair = listEntry->data; + replaceSpaceWithPlus(pair->key); + strcat(targetUrl, pair->key); + strcat(targetUrl, "="); + replaceSpaceWithPlus(pair->value); + strcat(targetUrl, pair->value); + if(listEntry->nextListEntry != NULL) { + strcat(targetUrl, "&"); + } + } + } + + return targetUrl; +} + +char *assembleHeaderField(char *key, char *value) { + char *header = malloc(strlen(key) + strlen(value) + 3); + + strcpy(header, key), + strcat(header, ": "); + strcat(header, value); + + return header; +} + +void postData(CURL *handle, char *bodyParameters) { + curl_easy_setopt(handle, CURLOPT_POSTFIELDS, bodyParameters); + curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE_LARGE, + strlen(bodyParameters)); +} + +int lengthOfKeyPair(keyValuePair_t *keyPair) { + long length = 0; + if((keyPair->key != NULL) && + (keyPair->value != NULL) ) + { + length = strlen(keyPair->key) + strlen(keyPair->value); + return length; + } + return 0; +} + + +void apiClient_invoke(apiClient_t *apiClient, + char *operationParameter, + list_t *queryParameters, + list_t *headerParameters, + list_t *formParameters, + list_t *headerType, + list_t *contentType, + char *bodyParameters, + char *requestType) { + CURL *handle = curl_easy_init(); + CURLcode res; + + if(handle) { + listEntry_t *listEntry; + curl_mime *mime = NULL; + struct curl_slist *headers = NULL; + char *buffContent = NULL; + char *buffHeader = NULL; + binary_t *fileVar = NULL; + char *formString = NULL; + + if(headerType != NULL) { + list_ForEach(listEntry, headerType) { + if(strstr((char *) listEntry->data, + "xml") == NULL) + { + buffHeader = malloc(strlen( + "Accept: ") + + strlen((char *) + listEntry-> + data) + 1); + sprintf(buffHeader, "%s%s", "Accept: ", + (char *) listEntry->data); + headers = curl_slist_append(headers, + buffHeader); + free(buffHeader); + } + } + } + if(contentType != NULL) { + list_ForEach(listEntry, contentType) { + if(strstr((char *) listEntry->data, + "xml") == NULL) + { + buffContent = + malloc(strlen( + "Content-Type: ") + strlen( + (char *) + listEntry->data) + + 1); + sprintf(buffContent, "%s%s", + "Content-Type: ", + (char *) listEntry->data); + headers = curl_slist_append(headers, + buffContent); + free(buffContent); + buffContent = NULL; + } + } + } else { + headers = curl_slist_append(headers, + "Content-Type: application/json"); + } + + if(requestType != NULL) { + curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, + requestType); + } + + if(formParameters != NULL) { + if(contentType && + findStrInStrList(contentType, "application/x-www-form-urlencoded") != NULL) + { + long parameterLength = 0; + long keyPairLength = 0; + list_ForEach(listEntry, formParameters) { + keyValuePair_t *keyPair = + listEntry->data; + + keyPairLength = + lengthOfKeyPair(keyPair) + 1; + + if(listEntry->nextListEntry != NULL) { + parameterLength++; + } + parameterLength = parameterLength + + keyPairLength; + } + + formString = malloc(parameterLength + 1); + memset(formString, 0, parameterLength + 1); + + list_ForEach(listEntry, formParameters) { + keyValuePair_t *keyPair = + listEntry->data; + if((keyPair->key != NULL) && + (keyPair->value != NULL) ) + { + strcat(formString, + keyPair->key); + strcat(formString, "="); + strcat(formString, + keyPair->value); + if(listEntry->nextListEntry != + NULL) + { + strcat(formString, "&"); + } + } + } + curl_easy_setopt(handle, CURLOPT_POSTFIELDS, + formString); + } + if(contentType && + findStrInStrList(contentType, "multipart/form-data") != NULL) { + mime = curl_mime_init(handle); + list_ForEach(listEntry, formParameters) { + keyValuePair_t *keyValuePair = + listEntry->data; + + if((keyValuePair->key != NULL) && + (keyValuePair->value != NULL) ) + { + curl_mimepart *part = + curl_mime_addpart(mime); + + curl_mime_name(part, + keyValuePair->key); + + + if(strcmp(keyValuePair->key, + "file") == 0) + { + memcpy(&fileVar, + keyValuePair->value, + sizeof(fileVar)); + curl_mime_data(part, + fileVar->data, + fileVar->len); + curl_mime_filename(part, + "image.png"); + } else { + curl_mime_data(part, + keyValuePair->value, + CURL_ZERO_TERMINATED); + } + } + } + curl_easy_setopt(handle, CURLOPT_MIMEPOST, + mime); + } + } + + list_ForEach(listEntry, headerParameters) { + keyValuePair_t *keyValuePair = listEntry->data; + if((keyValuePair->key != NULL) && + (keyValuePair->value != NULL) ) + { + char *headerValueToWrite = assembleHeaderField( + keyValuePair->key, keyValuePair->value); + curl_slist_append(headers, headerValueToWrite); + free(headerValueToWrite); + } + } + + if ( strstr(apiClient->basePath, "https") != NULL ) { + if ( apiClient->sslConfig ) { + if( apiClient->sslConfig->clientCertFile ) { + curl_easy_setopt(handle, CURLOPT_SSLCERT, apiClient->sslConfig->clientCertFile); + } + if( apiClient->sslConfig->clientKeyFile ) { + curl_easy_setopt(handle, CURLOPT_SSLKEY, apiClient->sslConfig->clientKeyFile); + } + if( apiClient->sslConfig->CACertFile ) { + curl_easy_setopt(handle, CURLOPT_CAINFO, apiClient->sslConfig->CACertFile); + } + if ( 1 == apiClient->sslConfig->insecureSkipTlsVerify ) { + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L); + } else { + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 1L); + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 2L); + } + } else { + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L); + } + } + + if (apiClient->progress_func != NULL) { + curl_easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, apiClient->progress_func); + if (apiClient->progress_data != NULL) { + curl_easy_setopt(handle, CURLOPT_XFERINFODATA, apiClient->progress_data); + } + curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0L); + } + + + char *targetUrl = + assembleTargetUrl(apiClient->basePath, + operationParameter, + queryParameters); + + curl_easy_setopt(handle, CURLOPT_URL, targetUrl); + curl_easy_setopt(handle, + CURLOPT_WRITEFUNCTION, + writeDataCallback); + curl_easy_setopt(handle, + CURLOPT_WRITEDATA, + apiClient); + curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(handle, CURLOPT_VERBOSE, 0); // to get curl debug msg 0: to disable, 1L:to enable + + + if(bodyParameters != NULL) { + postData(handle, bodyParameters); + } + + res = curl_easy_perform(handle); + + curl_slist_freeList_all(headers); + + free(targetUrl); + + if(res == CURLE_OK) { + curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &apiClient->response_code); + } else { + char *url,*ip,*scheme; + long port; + curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &url); + curl_easy_getinfo(handle, CURLINFO_PRIMARY_IP, &ip); + curl_easy_getinfo(handle, CURLINFO_PRIMARY_PORT, &port); + curl_easy_getinfo(handle, CURLINFO_SCHEME, &scheme); + fprintf(stderr, "curl_easy_perform() failed\n\nURL: %s\nIP: %s\nPORT: %li\nSCHEME: %s\nStrERROR: %s\n",url,ip,port,scheme, + curl_easy_strerror(res)); + } + + curl_easy_cleanup(handle); + if(formParameters != NULL) { + free(formString); + curl_mime_free(mime); + } + } +} + +size_t writeDataCallback(void *buffer, size_t size, size_t nmemb, void *userp) { + size_t size_this_time = nmemb * size; + apiClient_t *apiClient = (apiClient_t *)userp; + apiClient->dataReceived = (char *)realloc( apiClient->dataReceived, apiClient->dataReceivedLen + size_this_time + 1); + memcpy((char *)apiClient->dataReceived + apiClient->dataReceivedLen, buffer, size_this_time); + apiClient->dataReceivedLen += size_this_time; + ((char*)apiClient->dataReceived)[apiClient->dataReceivedLen] = '\0'; // the space size of (apiClient->dataReceived) = dataReceivedLen + 1 + if (apiClient->data_callback_func) { + apiClient->data_callback_func(&apiClient->dataReceived, &apiClient->dataReceivedLen); + } + return size_this_time; +} + +char *strReplace(char *orig, char *rep, char *with) { + char *result; // the return string + char *ins; // the next insert point + char *tmp; // varies + int lenRep; // length of rep (the string to remove) + int lenWith; // length of with (the string to replace rep with) + int lenFront; // distance between rep and end of last rep + int count; // number of replacements + + // sanity checks and initialization + if(!orig || !rep) + { + return NULL; + } + lenRep = strlen(rep); + if(lenRep == 0) { + return NULL; // empty rep causes infinite loop during count + } + if(!with) { + with = ""; + } + lenWith = strlen(with); + + // count the number of replacements needed + ins = orig; + for(count = 0; tmp = strstr(ins, rep); ++count) { + ins = tmp + lenRep; + } + + tmp = result = malloc(strlen(orig) + (lenWith - lenRep) * count + 1); + + if(!result) { + return NULL; + } + char *originalPointer = orig; // copying original pointer to free the memory + // first time through the loop, all the variable are set correctly + // from here on, + // tmp points to the end of the result string + // ins points to the next occurrence of rep in orig + // orig points to the remainder of orig after "end of rep" + while(count--) { + ins = strstr(orig, rep); + lenFront = ins - orig; + tmp = strncpy(tmp, orig, lenFront) + lenFront; + tmp = strcpy(tmp, with) + lenWith; + orig += lenFront + lenRep; // move to next "end of rep" + } + strcpy(tmp, orig); + free(originalPointer); + return result; +} + +void apiClient_setupGlobalEnv() { + curl_global_init(CURL_GLOBAL_ALL); +} + +void apiClient_unsetupGlobalEnv() { + curl_global_cleanup(); +} diff --git a/ems-cloud-mgmt-sdk/c/src/apiKey.c b/ems-cloud-mgmt-sdk/c/src/apiKey.c new file mode 100644 index 0000000000..eae9b75f3b --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/src/apiKey.c @@ -0,0 +1,20 @@ +#include +#include +#include "../include/keyValuePair.h" + +keyValuePair_t *keyValuePair_create(char *key, void *value) { + keyValuePair_t *keyValuePair = malloc(sizeof(keyValuePair_t)); + keyValuePair->key = key; + keyValuePair->value = value; + return keyValuePair; +} + +keyValuePair_t* keyValuePair_create_allocate(char* key, double value) { + double* boolpointer = malloc(sizeof(value)); + memcpy(boolpointer, &value, sizeof(value)); + return keyValuePair_create(key, boolpointer); +} + +void keyValuePair_free(keyValuePair_t *keyValuePair) { + free(keyValuePair); +} diff --git a/ems-cloud-mgmt-sdk/c/src/binary.c b/ems-cloud-mgmt-sdk/c/src/binary.c new file mode 100644 index 0000000000..ddd162a91f --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/src/binary.c @@ -0,0 +1,58 @@ +#include +#include +#include "../include/binary.h" +#ifdef OPENSSL +#include "openssl/pem.h" +#endif + +binary_t* instantiate_binary_t(char* data, int len) { + binary_t* ret = malloc(sizeof(struct binary_t)); + ret->len=len; + ret->data = malloc(len); + memcpy(ret->data, data, len); + return ret; +} + +char *base64encode (const void *b64_encode_this, int encode_this_many_bytes){ +#ifdef OPENSSL + BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. + BUF_MEM *mem_bio_mem_ptr; //Pointer to a "memory BIO" structure holding our base64 data. + b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. + mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory sink BIO. + BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-sink BIO chain. + BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less. + BIO_write(b64_bio, b64_encode_this, encode_this_many_bytes); //Records base64 encoded data. + BIO_flush(b64_bio); //Flush data. Necessary for b64 encoding, because of pad characters. + BIO_get_mem_ptr(mem_bio, &mem_bio_mem_ptr); //Store address of mem_bio's memory structure. + BIO_set_close(mem_bio, BIO_NOCLOSE); //Permit access to mem_ptr after BIOs are destroyed. + BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). + BUF_MEM_grow(mem_bio_mem_ptr, (*mem_bio_mem_ptr).length + 1); //Makes space for end null. + (*mem_bio_mem_ptr).data[(*mem_bio_mem_ptr).length] = '\0'; //Adds null-terminator to tail. + return (*mem_bio_mem_ptr).data; //Returns base-64 encoded data. (See: "buf_mem_st" struct). +#else // OPENSSL +#warning Data will not be encoded. If you want to use function "base64encode", please define "-DOPENSSL" when building the library. + return NULL; +#endif // OPENSSL +} + +char *base64decode (const void *b64_decode_this, int decode_this_many_bytes, int *decoded_bytes){ +#ifdef OPENSSL + BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO. + char *base64_decoded = calloc( (decode_this_many_bytes*3)/4+1, sizeof(char) ); //+1 = null. + b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO. + mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory source BIO. + BIO_write(mem_bio, b64_decode_this, decode_this_many_bytes); //Base64 data saved in source. + BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-source BIO chain. + BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines. + int decoded_byte_index = 0; //Index where the next base64_decoded byte should be written. + while ( 0 < BIO_read(b64_bio, base64_decoded+decoded_byte_index, 1) ){ //Read byte-by-byte. + decoded_byte_index++; //Increment the index until read of BIO decoded data is complete. + } //Once we're done reading decoded data, BIO_read returns -1 even though there's no error. + BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one). + *decoded_bytes = decoded_byte_index; + return base64_decoded; //Returns base-64 decoded data with trailing null terminator. +#else // OPENSSL +#warning Data will not be decoded. If you want to use function "base64decode", please define "-DOPENSSL" when building the library. + return NULL; +#endif // OPENSSL +} diff --git a/ems-cloud-mgmt-sdk/c/src/list.c b/ems-cloud-mgmt-sdk/c/src/list.c new file mode 100644 index 0000000000..786812158a --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/src/list.c @@ -0,0 +1,200 @@ +#include +#include +#include +#include + +#include "../include/list.h" +static listEntry_t *listEntry_create(void *data) { + listEntry_t *createdListEntry = malloc(sizeof(listEntry_t)); + if(createdListEntry == NULL) { + // TODO Malloc Failure + return NULL; + } + createdListEntry->data = data; + + return createdListEntry; +} + +void listEntry_free(listEntry_t *listEntry, void *additionalData) { + free(listEntry); +} + +void listEntry_printAsInt(listEntry_t *listEntry, void *additionalData) { + printf("%i\n", *((int *) (listEntry->data))); +} + +list_t *list_createList() { + list_t *createdList = malloc(sizeof(list_t)); + if(createdList == NULL) { + // TODO Malloc Failure + return NULL; + } + createdList->firstEntry = NULL; + createdList->lastEntry = NULL; + createdList->count = 0; + + return createdList; +} + +void list_iterateThroughListForward(list_t *list, + void (*operationToPerform)( + listEntry_t *, + void *callbackFunctionUsedData), + void *additionalDataNeededForCallbackFunction) +{ + listEntry_t *currentListEntry = list->firstEntry; + listEntry_t *nextListEntry; + + if(currentListEntry == NULL) { + return; + } + + nextListEntry = currentListEntry->nextListEntry; + + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + + while(currentListEntry != NULL) { + nextListEntry = currentListEntry->nextListEntry; + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + } +} + +void list_iterateThroughListBackward(list_t *list, + void (*operationToPerform)( + listEntry_t *, + void *callbackFunctionUsedData), + void *additionalDataNeededForCallbackFunction) +{ + listEntry_t *currentListEntry = list->lastEntry; + listEntry_t *nextListEntry = currentListEntry->prevListEntry; + + if(currentListEntry == NULL) { + return; + } + + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + + while(currentListEntry != NULL) { + nextListEntry = currentListEntry->prevListEntry; + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + } +} + +void list_freeList(list_t *list) { + if(list){ + list_iterateThroughListForward(list, listEntry_free, NULL); + free(list); + } +} + +void list_addElement(list_t *list, void *dataToAddInList) { + listEntry_t *newListEntry = listEntry_create(dataToAddInList); + if(newListEntry == NULL) { + // TODO Malloc Failure + return; + } + if(list->firstEntry == NULL) { + list->firstEntry = newListEntry; + list->lastEntry = newListEntry; + + newListEntry->prevListEntry = NULL; + newListEntry->nextListEntry = NULL; + + list->count++; + + return; + } + + list->lastEntry->nextListEntry = newListEntry; + newListEntry->prevListEntry = list->lastEntry; + newListEntry->nextListEntry = NULL; + list->lastEntry = newListEntry; + + list->count++; +} + +void list_removeElement(list_t *list, listEntry_t *elementToRemove) { + listEntry_t *elementBeforeElementToRemove = + elementToRemove->prevListEntry; + listEntry_t *elementAfterElementToRemove = + elementToRemove->nextListEntry; + + if(elementBeforeElementToRemove != NULL) { + elementBeforeElementToRemove->nextListEntry = + elementAfterElementToRemove; + } else { + list->firstEntry = elementAfterElementToRemove; + } + + if(elementAfterElementToRemove != NULL) { + elementAfterElementToRemove->prevListEntry = + elementBeforeElementToRemove; + } else { + list->lastEntry = elementBeforeElementToRemove; + } + + listEntry_free(elementToRemove, NULL); + + list->count--; +} + +listEntry_t *list_getElementAt(list_t *list, long indexOfElement) { + listEntry_t *currentListEntry; + + if((list->count / 2) > indexOfElement) { + currentListEntry = list->firstEntry; + + for(int i = 0; i < indexOfElement; i++) { + currentListEntry = currentListEntry->nextListEntry; + } + + return currentListEntry; + } else { + currentListEntry = list->lastEntry; + + for(int i = 1; i < (list->count - indexOfElement); i++) { + currentListEntry = currentListEntry->prevListEntry; + } + + return currentListEntry; + } +} + +char* findStrInStrList(list_t *strList, const char *str) +{ + if (!strList || !str) { + return NULL; + } + + listEntry_t* listEntry = NULL; + list_ForEach(listEntry, strList) { + if (strstr((char*)listEntry->data, str) != NULL) { + return (char*)listEntry->data; + } + } + + return NULL; +} + +void clear_and_free_string_list(list_t *list) +{ + if (!list) { + return; + } + + listEntry_t *listEntry = NULL; + list_ForEach(listEntry, list) { + char *list_item = listEntry->data; + free(list_item); + list_item = NULL; + } + list_freeList(list); +} \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/c/uncrustify-rules.cfg b/ems-cloud-mgmt-sdk/c/uncrustify-rules.cfg new file mode 100644 index 0000000000..fa6d5bfb31 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/uncrustify-rules.cfg @@ -0,0 +1,210 @@ +tok_split_gte=false +utf8_byte=false +utf8_force=true +indent_cmt_with_tabs=false +indent_align_string=false +indent_braces=false +indent_braces_no_func=false +indent_braces_no_class=false +indent_braces_no_struct=false +indent_brace_parent=false +indent_namespace=false +indent_extern=true +indent_class=false +indent_class_colon=false +indent_else_if=false +indent_var_def_cont=false +indent_func_call_param=false +indent_func_def_param=false +indent_func_proto_param=false +indent_func_class_param=false +indent_func_ctor_var_param=false +indent_template_param=false +indent_func_param_double=false +indent_relative_single_line_comments=false +indent_col1_comment=false +indent_access_spec_body=false +indent_paren_nl=false +indent_comma_paren=false +indent_bool_paren=false +indent_first_bool_expr=false +indent_square_nl=false +indent_preserve_sql=false +indent_align_assign=true +sp_balance_nested_parens=false +align_keep_tabs=false +align_with_tabs=true +align_on_tabstop=true +align_func_params=true +align_same_func_call_params=false +align_var_def_colon=false +align_var_def_attribute=false +align_var_def_inline=false +align_right_cmt_mix=false +align_on_operator=false +align_mix_var_proto=false +align_single_line_func=false +align_single_line_brace=false +align_nl_cont=false +align_left_shift=true +align_oc_decl_colon=false +nl_collapse_empty_body=true +nl_assign_leave_one_liners=false +nl_class_leave_one_liners=false +nl_enum_leave_one_liners=false +nl_getset_leave_one_liners=false +nl_func_leave_one_liners=false +nl_if_leave_one_liners=false +nl_multi_line_cond=true +nl_multi_line_define=false +nl_before_case=true +nl_after_case=true +nl_after_return=false +nl_after_semicolon=true +nl_after_brace_open=false +nl_after_brace_open_cmt=false +nl_after_vbrace_open=false +nl_after_vbrace_open_empty=false +nl_after_brace_close=false +nl_after_vbrace_close=false +nl_define_macro=false +nl_squeeze_ifdef=false +nl_ds_struct_enum_cmt=false +nl_ds_struct_enum_close_brace=false +nl_create_if_one_liner=false +nl_create_for_one_liner=false +nl_create_while_one_liner=false +ls_for_split_full=false +ls_func_split_full=false +nl_after_multiline_comment=false +eat_blanks_after_open_brace=true +eat_blanks_before_close_brace=true +mod_full_brace_if_chain=false +mod_pawn_semicolon=false +mod_full_paren_if_bool=true +mod_remove_extra_semicolon=true +mod_sort_import=true +mod_sort_using=false +mod_sort_include=false +mod_move_case_break=false +mod_remove_empty_return=true +cmt_indent_multi=true +cmt_c_group=false +cmt_c_nl_start=true +cmt_c_nl_end=true +cmt_cpp_group=false +cmt_cpp_nl_start=true +cmt_cpp_nl_end=true +cmt_cpp_to_c=false +cmt_star_cont=false +cmt_multi_check_last=true +cmt_insert_before_preproc=false +pp_indent_at_level=false +pp_region_indent_code=false +pp_if_indent_code=false +pp_define_at_level=false +align_var_def_star_style=1 +align_var_def_amp_style=0 +code_width=80 +indent_with_tabs=1 +sp_arith=force +sp_assign=force +sp_assign_default=force +sp_enum_assign=force +sp_bool=force +sp_compare=force +sp_inside_paren=remove +sp_before_ptr_star=force +sp_before_unnamed_ptr_star=force +sp_between_ptr_star=remove +sp_after_ptr_star=remove +sp_before_sparen=remove +sp_inside_sparen=remove +sp_sparen_brace=force +sp_before_semi=remove +sp_before_semi_for_empty=force +sp_after_semi=force +sp_after_semi_for=force +sp_after_semi_for_empty=force +sp_before_square=remove +sp_before_squares=remove +sp_inside_square=remove +sp_after_comma=force +sp_before_comma=remove +sp_paren_comma=force +sp_before_case_colon=remove +sp_after_cast=force +sp_inside_paren_cast=remove +sp_sizeof_paren=remove +sp_inside_braces_struct=force +sp_type_func=remove +sp_func_proto_paren=remove +sp_func_def_paren=remove +sp_inside_fparens=remove +sp_inside_fparen=remove +sp_square_fparen=remove +sp_fparen_brace=force +sp_func_call_paren=remove +sp_attribute_paren=remove +sp_defined_paren=remove +sp_macro=force +sp_macro_func=force +sp_else_brace=force +sp_brace_else=force +sp_brace_typedef=force +sp_not=remove +sp_inv=remove +sp_addr=remove +sp_member=remove +sp_deref=remove +sp_sign=remove +sp_incdec=remove +sp_before_nl_cont=force +sp_cond_colon=force +sp_cond_question=force +sp_case_label=force +sp_cmt_cpp_start=force +sp_endif_cmt=force +sp_before_tr_emb_cmt=force +nl_start_of_file=remove +nl_end_of_file=add +nl_assign_brace=remove +nl_enum_brace=remove +nl_struct_brace=remove +nl_union_brace=remove +nl_if_brace=remove +nl_brace_else=remove +nl_elseif_brace=remove +nl_else_brace=remove +nl_else_if=remove +nl_brace_finally=remove +nl_finally_brace=remove +nl_try_brace=remove +nl_for_brace=remove +nl_catch_brace=remove +nl_brace_catch=remove +nl_while_brace=remove +nl_do_brace=remove +nl_brace_while=remove +nl_switch_brace=remove +nl_class_brace=remove +nl_func_type_name=remove +nl_func_proto_type_name=remove +nl_func_paren=remove +nl_func_def_paren=remove +nl_func_decl_start=remove +nl_func_def_start=remove +nl_func_decl_args=remove +nl_func_def_args=remove +nl_func_decl_end=remove +nl_func_def_end=remove +nl_func_decl_empty=remove +nl_func_def_empty=remove +nl_fdef_brace=remove +nl_return_expr=remove +pos_bool=trail_break +mod_full_brace_do=force +mod_full_brace_for=force +mod_full_brace_if=force +mod_full_brace_while=force +mod_paren_on_return=remove \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_balance.c b/ems-cloud-mgmt-sdk/c/unit-test/test_balance.c new file mode 100644 index 0000000000..dfff316844 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_balance.c @@ -0,0 +1,60 @@ +#ifndef balance_TEST +#define balance_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define balance_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/balance.h" +balance_t* instantiate_balance(int include_optional); + + + +balance_t* instantiate_balance(int include_optional) { + balance_t* balance = NULL; + if (include_optional) { + balance = balance_create( + "KRAKEN", + list_createList() + ); + } else { + balance = balance_create( + "KRAKEN", + list_createList() + ); + } + + return balance; +} + + +#ifdef balance_MAIN + +void test_balance(int include_optional) { + balance_t* balance_1 = instantiate_balance(include_optional); + + cJSON* jsonbalance_1 = balance_convertToJSON(balance_1); + printf("balance :\n%s\n", cJSON_Print(jsonbalance_1)); + balance_t* balance_2 = balance_parseFromJSON(jsonbalance_1); + cJSON* jsonbalance_2 = balance_convertToJSON(balance_2); + printf("repeating balance:\n%s\n", cJSON_Print(jsonbalance_2)); +} + +int main() { + test_balance(1); + test_balance(0); + + printf("Hello world \n"); + return 0; +} + +#endif // balance_MAIN +#endif // balance_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_balance_data.c b/ems-cloud-mgmt-sdk/c/unit-test/test_balance_data.c new file mode 100644 index 0000000000..19304767c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_balance_data.c @@ -0,0 +1,72 @@ +#ifndef balance_data_TEST +#define balance_data_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define balance_data_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/balance_data.h" +balance_data_t* instantiate_balance_data(int include_optional); + + + +balance_data_t* instantiate_balance_data(int include_optional) { + balance_data_t* balance_data = NULL; + if (include_optional) { + balance_data = balance_data_create( + "XBT", + "BTC", + 0.00134444, + 0.00134444, + 0.0, + ems___rest_api_balance_data_LASTUPDATEDBY_"EXCHANGE", + 1355.12, + 0.007 + ); + } else { + balance_data = balance_data_create( + "XBT", + "BTC", + 0.00134444, + 0.00134444, + 0.0, + ems___rest_api_balance_data_LASTUPDATEDBY_"EXCHANGE", + 1355.12, + 0.007 + ); + } + + return balance_data; +} + + +#ifdef balance_data_MAIN + +void test_balance_data(int include_optional) { + balance_data_t* balance_data_1 = instantiate_balance_data(include_optional); + + cJSON* jsonbalance_data_1 = balance_data_convertToJSON(balance_data_1); + printf("balance_data :\n%s\n", cJSON_Print(jsonbalance_data_1)); + balance_data_t* balance_data_2 = balance_data_parseFromJSON(jsonbalance_data_1); + cJSON* jsonbalance_data_2 = balance_data_convertToJSON(balance_data_2); + printf("repeating balance_data:\n%s\n", cJSON_Print(jsonbalance_data_2)); +} + +int main() { + test_balance_data(1); + test_balance_data(0); + + printf("Hello world \n"); + return 0; +} + +#endif // balance_data_MAIN +#endif // balance_data_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_fills.c b/ems-cloud-mgmt-sdk/c/unit-test/test_fills.c new file mode 100644 index 0000000000..25d3c878c4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_fills.c @@ -0,0 +1,62 @@ +#ifndef fills_TEST +#define fills_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define fills_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/fills.h" +fills_t* instantiate_fills(int include_optional); + + + +fills_t* instantiate_fills(int include_optional) { + fills_t* fills = NULL; + if (include_optional) { + fills = fills_create( + 2020-01-01T10:45:20.1677709Z, + 10799.2, + 0.002 + ); + } else { + fills = fills_create( + 2020-01-01T10:45:20.1677709Z, + 10799.2, + 0.002 + ); + } + + return fills; +} + + +#ifdef fills_MAIN + +void test_fills(int include_optional) { + fills_t* fills_1 = instantiate_fills(include_optional); + + cJSON* jsonfills_1 = fills_convertToJSON(fills_1); + printf("fills :\n%s\n", cJSON_Print(jsonfills_1)); + fills_t* fills_2 = fills_parseFromJSON(jsonfills_1); + cJSON* jsonfills_2 = fills_convertToJSON(fills_2); + printf("repeating fills:\n%s\n", cJSON_Print(jsonfills_2)); +} + +int main() { + test_fills(1); + test_fills(0); + + printf("Hello world \n"); + return 0; +} + +#endif // fills_MAIN +#endif // fills_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_message_reject.c b/ems-cloud-mgmt-sdk/c/unit-test/test_message_reject.c new file mode 100644 index 0000000000..e8638c50c0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_message_reject.c @@ -0,0 +1,66 @@ +#ifndef message_reject_TEST +#define message_reject_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define message_reject_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/message_reject.h" +message_reject_t* instantiate_message_reject(int include_optional); + + + +message_reject_t* instantiate_message_reject(int include_optional) { + message_reject_t* message_reject = NULL; + if (include_optional) { + message_reject = message_reject_create( + "MESSAGE_REJECT", + ems___rest_api_message_reject__"ORDER_ID_NOT_FOUND", + "BINANCE", + "Order with ID: BINANCE-7d8a-4888 not found", + "{"client_order_id":"BINANCE-7d8a-4888","exchange_id":"BINANCE","type":"ORDER_CANCEL_SINGLE_REQUEST"}" + ); + } else { + message_reject = message_reject_create( + "MESSAGE_REJECT", + ems___rest_api_message_reject__"ORDER_ID_NOT_FOUND", + "BINANCE", + "Order with ID: BINANCE-7d8a-4888 not found", + "{"client_order_id":"BINANCE-7d8a-4888","exchange_id":"BINANCE","type":"ORDER_CANCEL_SINGLE_REQUEST"}" + ); + } + + return message_reject; +} + + +#ifdef message_reject_MAIN + +void test_message_reject(int include_optional) { + message_reject_t* message_reject_1 = instantiate_message_reject(include_optional); + + cJSON* jsonmessage_reject_1 = message_reject_convertToJSON(message_reject_1); + printf("message_reject :\n%s\n", cJSON_Print(jsonmessage_reject_1)); + message_reject_t* message_reject_2 = message_reject_parseFromJSON(jsonmessage_reject_1); + cJSON* jsonmessage_reject_2 = message_reject_convertToJSON(message_reject_2); + printf("repeating message_reject:\n%s\n", cJSON_Print(jsonmessage_reject_2)); +} + +int main() { + test_message_reject(1); + test_message_reject(0); + + printf("Hello world \n"); + return 0; +} + +#endif // message_reject_MAIN +#endif // message_reject_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_ord_side.c b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_side.c new file mode 100644 index 0000000000..982b850a61 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_side.c @@ -0,0 +1,56 @@ +#ifndef ord_side_TEST +#define ord_side_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define ord_side_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/ord_side.h" +ord_side_t* instantiate_ord_side(int include_optional); + + + +ord_side_t* instantiate_ord_side(int include_optional) { + ord_side_t* ord_side = NULL; + if (include_optional) { + ord_side = ord_side_create( + ); + } else { + ord_side = ord_side_create( + ); + } + + return ord_side; +} + + +#ifdef ord_side_MAIN + +void test_ord_side(int include_optional) { + ord_side_t* ord_side_1 = instantiate_ord_side(include_optional); + + cJSON* jsonord_side_1 = ord_side_convertToJSON(ord_side_1); + printf("ord_side :\n%s\n", cJSON_Print(jsonord_side_1)); + ord_side_t* ord_side_2 = ord_side_parseFromJSON(jsonord_side_1); + cJSON* jsonord_side_2 = ord_side_convertToJSON(ord_side_2); + printf("repeating ord_side:\n%s\n", cJSON_Print(jsonord_side_2)); +} + +int main() { + test_ord_side(1); + test_ord_side(0); + + printf("Hello world \n"); + return 0; +} + +#endif // ord_side_MAIN +#endif // ord_side_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_ord_status.c b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_status.c new file mode 100644 index 0000000000..12a4a21fdc --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_status.c @@ -0,0 +1,56 @@ +#ifndef ord_status_TEST +#define ord_status_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define ord_status_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/ord_status.h" +ord_status_t* instantiate_ord_status(int include_optional); + + + +ord_status_t* instantiate_ord_status(int include_optional) { + ord_status_t* ord_status = NULL; + if (include_optional) { + ord_status = ord_status_create( + ); + } else { + ord_status = ord_status_create( + ); + } + + return ord_status; +} + + +#ifdef ord_status_MAIN + +void test_ord_status(int include_optional) { + ord_status_t* ord_status_1 = instantiate_ord_status(include_optional); + + cJSON* jsonord_status_1 = ord_status_convertToJSON(ord_status_1); + printf("ord_status :\n%s\n", cJSON_Print(jsonord_status_1)); + ord_status_t* ord_status_2 = ord_status_parseFromJSON(jsonord_status_1); + cJSON* jsonord_status_2 = ord_status_convertToJSON(ord_status_2); + printf("repeating ord_status:\n%s\n", cJSON_Print(jsonord_status_2)); +} + +int main() { + test_ord_status(1); + test_ord_status(0); + + printf("Hello world \n"); + return 0; +} + +#endif // ord_status_MAIN +#endif // ord_status_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_ord_type.c b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_type.c new file mode 100644 index 0000000000..147dcd2bf1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_ord_type.c @@ -0,0 +1,56 @@ +#ifndef ord_type_TEST +#define ord_type_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define ord_type_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/ord_type.h" +ord_type_t* instantiate_ord_type(int include_optional); + + + +ord_type_t* instantiate_ord_type(int include_optional) { + ord_type_t* ord_type = NULL; + if (include_optional) { + ord_type = ord_type_create( + ); + } else { + ord_type = ord_type_create( + ); + } + + return ord_type; +} + + +#ifdef ord_type_MAIN + +void test_ord_type(int include_optional) { + ord_type_t* ord_type_1 = instantiate_ord_type(include_optional); + + cJSON* jsonord_type_1 = ord_type_convertToJSON(ord_type_1); + printf("ord_type :\n%s\n", cJSON_Print(jsonord_type_1)); + ord_type_t* ord_type_2 = ord_type_parseFromJSON(jsonord_type_1); + cJSON* jsonord_type_2 = ord_type_convertToJSON(ord_type_2); + printf("repeating ord_type:\n%s\n", cJSON_Print(jsonord_type_2)); +} + +int main() { + test_ord_type(1); + test_ord_type(0); + + printf("Hello world \n"); + return 0; +} + +#endif // ord_type_MAIN +#endif // ord_type_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_all_request.c b/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_all_request.c new file mode 100644 index 0000000000..85eb4f1418 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_all_request.c @@ -0,0 +1,58 @@ +#ifndef order_cancel_all_request_TEST +#define order_cancel_all_request_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define order_cancel_all_request_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/order_cancel_all_request.h" +order_cancel_all_request_t* instantiate_order_cancel_all_request(int include_optional); + + + +order_cancel_all_request_t* instantiate_order_cancel_all_request(int include_optional) { + order_cancel_all_request_t* order_cancel_all_request = NULL; + if (include_optional) { + order_cancel_all_request = order_cancel_all_request_create( + "KRAKEN" + ); + } else { + order_cancel_all_request = order_cancel_all_request_create( + "KRAKEN" + ); + } + + return order_cancel_all_request; +} + + +#ifdef order_cancel_all_request_MAIN + +void test_order_cancel_all_request(int include_optional) { + order_cancel_all_request_t* order_cancel_all_request_1 = instantiate_order_cancel_all_request(include_optional); + + cJSON* jsonorder_cancel_all_request_1 = order_cancel_all_request_convertToJSON(order_cancel_all_request_1); + printf("order_cancel_all_request :\n%s\n", cJSON_Print(jsonorder_cancel_all_request_1)); + order_cancel_all_request_t* order_cancel_all_request_2 = order_cancel_all_request_parseFromJSON(jsonorder_cancel_all_request_1); + cJSON* jsonorder_cancel_all_request_2 = order_cancel_all_request_convertToJSON(order_cancel_all_request_2); + printf("repeating order_cancel_all_request:\n%s\n", cJSON_Print(jsonorder_cancel_all_request_2)); +} + +int main() { + test_order_cancel_all_request(1); + test_order_cancel_all_request(0); + + printf("Hello world \n"); + return 0; +} + +#endif // order_cancel_all_request_MAIN +#endif // order_cancel_all_request_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_single_request.c b/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_single_request.c new file mode 100644 index 0000000000..579c765608 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_order_cancel_single_request.c @@ -0,0 +1,62 @@ +#ifndef order_cancel_single_request_TEST +#define order_cancel_single_request_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define order_cancel_single_request_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/order_cancel_single_request.h" +order_cancel_single_request_t* instantiate_order_cancel_single_request(int include_optional); + + + +order_cancel_single_request_t* instantiate_order_cancel_single_request(int include_optional) { + order_cancel_single_request_t* order_cancel_single_request = NULL; + if (include_optional) { + order_cancel_single_request = order_cancel_single_request_create( + "KRAKEN", + "3456456754", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b" + ); + } else { + order_cancel_single_request = order_cancel_single_request_create( + "KRAKEN", + "3456456754", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b" + ); + } + + return order_cancel_single_request; +} + + +#ifdef order_cancel_single_request_MAIN + +void test_order_cancel_single_request(int include_optional) { + order_cancel_single_request_t* order_cancel_single_request_1 = instantiate_order_cancel_single_request(include_optional); + + cJSON* jsonorder_cancel_single_request_1 = order_cancel_single_request_convertToJSON(order_cancel_single_request_1); + printf("order_cancel_single_request :\n%s\n", cJSON_Print(jsonorder_cancel_single_request_1)); + order_cancel_single_request_t* order_cancel_single_request_2 = order_cancel_single_request_parseFromJSON(jsonorder_cancel_single_request_1); + cJSON* jsonorder_cancel_single_request_2 = order_cancel_single_request_convertToJSON(order_cancel_single_request_2); + printf("repeating order_cancel_single_request:\n%s\n", cJSON_Print(jsonorder_cancel_single_request_2)); +} + +int main() { + test_order_cancel_single_request(1); + test_order_cancel_single_request(0); + + printf("Hello world \n"); + return 0; +} + +#endif // order_cancel_single_request_MAIN +#endif // order_cancel_single_request_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report.c b/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report.c new file mode 100644 index 0000000000..f406b55673 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report.c @@ -0,0 +1,96 @@ +#ifndef order_execution_report_TEST +#define order_execution_report_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define order_execution_report_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/order_execution_report.h" +order_execution_report_t* instantiate_order_execution_report(int include_optional); + + + +order_execution_report_t* instantiate_order_execution_report(int include_optional) { + order_execution_report_t* order_execution_report = NULL; + if (include_optional) { + order_execution_report = order_execution_report_create( + "KRAKEN", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", + "XBT/USDT", + "KRAKEN_SPOT_BTC_USDT", + 0.045, + 0.0783, + ems___rest_api_order_execution_report__"BUY", + ems___rest_api_order_execution_report__"LIMIT", + ems___rest_api_order_execution_report__"GOOD_TILL_CANCEL", + 2020-01-01T10:45:20.1677709Z, + ["MAKER_OR_CANCEL"], + "f81211e2-27c4-b86a-8143-01088ba9222c", + "3456456754", + 0.22, + 0.0, + 0.0783, + ems___rest_api_order_execution_report__RECEIVED, + list_createList(), + "{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol 'BTCUSD' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}", + list_createList() + ); + } else { + order_execution_report = order_execution_report_create( + "KRAKEN", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", + "XBT/USDT", + "KRAKEN_SPOT_BTC_USDT", + 0.045, + 0.0783, + ems___rest_api_order_execution_report__"BUY", + ems___rest_api_order_execution_report__"LIMIT", + ems___rest_api_order_execution_report__"GOOD_TILL_CANCEL", + 2020-01-01T10:45:20.1677709Z, + ["MAKER_OR_CANCEL"], + "f81211e2-27c4-b86a-8143-01088ba9222c", + "3456456754", + 0.22, + 0.0, + 0.0783, + ems___rest_api_order_execution_report__RECEIVED, + list_createList(), + "{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol 'BTCUSD' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}", + list_createList() + ); + } + + return order_execution_report; +} + + +#ifdef order_execution_report_MAIN + +void test_order_execution_report(int include_optional) { + order_execution_report_t* order_execution_report_1 = instantiate_order_execution_report(include_optional); + + cJSON* jsonorder_execution_report_1 = order_execution_report_convertToJSON(order_execution_report_1); + printf("order_execution_report :\n%s\n", cJSON_Print(jsonorder_execution_report_1)); + order_execution_report_t* order_execution_report_2 = order_execution_report_parseFromJSON(jsonorder_execution_report_1); + cJSON* jsonorder_execution_report_2 = order_execution_report_convertToJSON(order_execution_report_2); + printf("repeating order_execution_report:\n%s\n", cJSON_Print(jsonorder_execution_report_2)); +} + +int main() { + test_order_execution_report(1); + test_order_execution_report(0); + + printf("Hello world \n"); + return 0; +} + +#endif // order_execution_report_MAIN +#endif // order_execution_report_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report_all_of.c b/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report_all_of.c new file mode 100644 index 0000000000..7aadcfedfb --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_order_execution_report_all_of.c @@ -0,0 +1,74 @@ +#ifndef order_execution_report_all_of_TEST +#define order_execution_report_all_of_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define order_execution_report_all_of_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/order_execution_report_all_of.h" +order_execution_report_all_of_t* instantiate_order_execution_report_all_of(int include_optional); + + + +order_execution_report_all_of_t* instantiate_order_execution_report_all_of(int include_optional) { + order_execution_report_all_of_t* order_execution_report_all_of = NULL; + if (include_optional) { + order_execution_report_all_of = order_execution_report_all_of_create( + "f81211e2-27c4-b86a-8143-01088ba9222c", + "3456456754", + 0.22, + 0.0, + 0.0783, + ems___rest_api_order_execution_report_all_of__RECEIVED, + list_createList(), + "{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol 'BTCUSD' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}", + list_createList() + ); + } else { + order_execution_report_all_of = order_execution_report_all_of_create( + "f81211e2-27c4-b86a-8143-01088ba9222c", + "3456456754", + 0.22, + 0.0, + 0.0783, + ems___rest_api_order_execution_report_all_of__RECEIVED, + list_createList(), + "{"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol 'BTCUSD' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"}", + list_createList() + ); + } + + return order_execution_report_all_of; +} + + +#ifdef order_execution_report_all_of_MAIN + +void test_order_execution_report_all_of(int include_optional) { + order_execution_report_all_of_t* order_execution_report_all_of_1 = instantiate_order_execution_report_all_of(include_optional); + + cJSON* jsonorder_execution_report_all_of_1 = order_execution_report_all_of_convertToJSON(order_execution_report_all_of_1); + printf("order_execution_report_all_of :\n%s\n", cJSON_Print(jsonorder_execution_report_all_of_1)); + order_execution_report_all_of_t* order_execution_report_all_of_2 = order_execution_report_all_of_parseFromJSON(jsonorder_execution_report_all_of_1); + cJSON* jsonorder_execution_report_all_of_2 = order_execution_report_all_of_convertToJSON(order_execution_report_all_of_2); + printf("repeating order_execution_report_all_of:\n%s\n", cJSON_Print(jsonorder_execution_report_all_of_2)); +} + +int main() { + test_order_execution_report_all_of(1); + test_order_execution_report_all_of(0); + + printf("Hello world \n"); + return 0; +} + +#endif // order_execution_report_all_of_MAIN +#endif // order_execution_report_all_of_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_order_new_single_request.c b/ems-cloud-mgmt-sdk/c/unit-test/test_order_new_single_request.c new file mode 100644 index 0000000000..a205eaa029 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_order_new_single_request.c @@ -0,0 +1,78 @@ +#ifndef order_new_single_request_TEST +#define order_new_single_request_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define order_new_single_request_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/order_new_single_request.h" +order_new_single_request_t* instantiate_order_new_single_request(int include_optional); + + + +order_new_single_request_t* instantiate_order_new_single_request(int include_optional) { + order_new_single_request_t* order_new_single_request = NULL; + if (include_optional) { + order_new_single_request = order_new_single_request_create( + "KRAKEN", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", + "XBT/USDT", + "KRAKEN_SPOT_BTC_USDT", + 0.045, + 0.0783, + ems___rest_api_order_new_single_request__"BUY", + ems___rest_api_order_new_single_request__"LIMIT", + ems___rest_api_order_new_single_request__"GOOD_TILL_CANCEL", + 2020-01-01T10:45:20.1677709Z, + ["MAKER_OR_CANCEL"] + ); + } else { + order_new_single_request = order_new_single_request_create( + "KRAKEN", + "6ab36bc1-344d-432e-ac6d-0bf44ee64c2b", + "XBT/USDT", + "KRAKEN_SPOT_BTC_USDT", + 0.045, + 0.0783, + ems___rest_api_order_new_single_request__"BUY", + ems___rest_api_order_new_single_request__"LIMIT", + ems___rest_api_order_new_single_request__"GOOD_TILL_CANCEL", + 2020-01-01T10:45:20.1677709Z, + ["MAKER_OR_CANCEL"] + ); + } + + return order_new_single_request; +} + + +#ifdef order_new_single_request_MAIN + +void test_order_new_single_request(int include_optional) { + order_new_single_request_t* order_new_single_request_1 = instantiate_order_new_single_request(include_optional); + + cJSON* jsonorder_new_single_request_1 = order_new_single_request_convertToJSON(order_new_single_request_1); + printf("order_new_single_request :\n%s\n", cJSON_Print(jsonorder_new_single_request_1)); + order_new_single_request_t* order_new_single_request_2 = order_new_single_request_parseFromJSON(jsonorder_new_single_request_1); + cJSON* jsonorder_new_single_request_2 = order_new_single_request_convertToJSON(order_new_single_request_2); + printf("repeating order_new_single_request:\n%s\n", cJSON_Print(jsonorder_new_single_request_2)); +} + +int main() { + test_order_new_single_request(1); + test_order_new_single_request(0); + + printf("Hello world \n"); + return 0; +} + +#endif // order_new_single_request_MAIN +#endif // order_new_single_request_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_position.c b/ems-cloud-mgmt-sdk/c/unit-test/test_position.c new file mode 100644 index 0000000000..4e767cfdd4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_position.c @@ -0,0 +1,60 @@ +#ifndef position_TEST +#define position_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define position_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/position.h" +position_t* instantiate_position(int include_optional); + + + +position_t* instantiate_position(int include_optional) { + position_t* position = NULL; + if (include_optional) { + position = position_create( + "KRAKEN", + list_createList() + ); + } else { + position = position_create( + "KRAKEN", + list_createList() + ); + } + + return position; +} + + +#ifdef position_MAIN + +void test_position(int include_optional) { + position_t* position_1 = instantiate_position(include_optional); + + cJSON* jsonposition_1 = position_convertToJSON(position_1); + printf("position :\n%s\n", cJSON_Print(jsonposition_1)); + position_t* position_2 = position_parseFromJSON(jsonposition_1); + cJSON* jsonposition_2 = position_convertToJSON(position_2); + printf("repeating position:\n%s\n", cJSON_Print(jsonposition_2)); +} + +int main() { + test_position(1); + test_position(0); + + printf("Hello world \n"); + return 0; +} + +#endif // position_MAIN +#endif // position_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_position_data.c b/ems-cloud-mgmt-sdk/c/unit-test/test_position_data.c new file mode 100644 index 0000000000..3d5d7271f9 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_position_data.c @@ -0,0 +1,76 @@ +#ifndef position_data_TEST +#define position_data_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define position_data_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/position_data.h" +position_data_t* instantiate_position_data(int include_optional); + + + +position_data_t* instantiate_position_data(int include_optional) { + position_data_t* position_data = NULL; + if (include_optional) { + position_data = position_data_create( + "XBTUSD", + "BITMEX_PERP_BTC_USD", + 0.00134444, + 7, + ems___rest_api_position_data__"BUY", + 0.0, + 0.0, + true, + 0.072323, + Other information provided by the exchange on this position. + ); + } else { + position_data = position_data_create( + "XBTUSD", + "BITMEX_PERP_BTC_USD", + 0.00134444, + 7, + ems___rest_api_position_data__"BUY", + 0.0, + 0.0, + true, + 0.072323, + Other information provided by the exchange on this position. + ); + } + + return position_data; +} + + +#ifdef position_data_MAIN + +void test_position_data(int include_optional) { + position_data_t* position_data_1 = instantiate_position_data(include_optional); + + cJSON* jsonposition_data_1 = position_data_convertToJSON(position_data_1); + printf("position_data :\n%s\n", cJSON_Print(jsonposition_data_1)); + position_data_t* position_data_2 = position_data_parseFromJSON(jsonposition_data_1); + cJSON* jsonposition_data_2 = position_data_convertToJSON(position_data_2); + printf("repeating position_data:\n%s\n", cJSON_Print(jsonposition_data_2)); +} + +int main() { + test_position_data(1); + test_position_data(0); + + printf("Hello world \n"); + return 0; +} + +#endif // position_data_MAIN +#endif // position_data_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_reject_reason.c b/ems-cloud-mgmt-sdk/c/unit-test/test_reject_reason.c new file mode 100644 index 0000000000..74e8ada091 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_reject_reason.c @@ -0,0 +1,56 @@ +#ifndef reject_reason_TEST +#define reject_reason_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define reject_reason_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/reject_reason.h" +reject_reason_t* instantiate_reject_reason(int include_optional); + + + +reject_reason_t* instantiate_reject_reason(int include_optional) { + reject_reason_t* reject_reason = NULL; + if (include_optional) { + reject_reason = reject_reason_create( + ); + } else { + reject_reason = reject_reason_create( + ); + } + + return reject_reason; +} + + +#ifdef reject_reason_MAIN + +void test_reject_reason(int include_optional) { + reject_reason_t* reject_reason_1 = instantiate_reject_reason(include_optional); + + cJSON* jsonreject_reason_1 = reject_reason_convertToJSON(reject_reason_1); + printf("reject_reason :\n%s\n", cJSON_Print(jsonreject_reason_1)); + reject_reason_t* reject_reason_2 = reject_reason_parseFromJSON(jsonreject_reason_1); + cJSON* jsonreject_reason_2 = reject_reason_convertToJSON(reject_reason_2); + printf("repeating reject_reason:\n%s\n", cJSON_Print(jsonreject_reason_2)); +} + +int main() { + test_reject_reason(1); + test_reject_reason(0); + + printf("Hello world \n"); + return 0; +} + +#endif // reject_reason_MAIN +#endif // reject_reason_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_time_in_force.c b/ems-cloud-mgmt-sdk/c/unit-test/test_time_in_force.c new file mode 100644 index 0000000000..6ae7d5de31 --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_time_in_force.c @@ -0,0 +1,56 @@ +#ifndef time_in_force_TEST +#define time_in_force_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define time_in_force_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/time_in_force.h" +time_in_force_t* instantiate_time_in_force(int include_optional); + + + +time_in_force_t* instantiate_time_in_force(int include_optional) { + time_in_force_t* time_in_force = NULL; + if (include_optional) { + time_in_force = time_in_force_create( + ); + } else { + time_in_force = time_in_force_create( + ); + } + + return time_in_force; +} + + +#ifdef time_in_force_MAIN + +void test_time_in_force(int include_optional) { + time_in_force_t* time_in_force_1 = instantiate_time_in_force(include_optional); + + cJSON* jsontime_in_force_1 = time_in_force_convertToJSON(time_in_force_1); + printf("time_in_force :\n%s\n", cJSON_Print(jsontime_in_force_1)); + time_in_force_t* time_in_force_2 = time_in_force_parseFromJSON(jsontime_in_force_1); + cJSON* jsontime_in_force_2 = time_in_force_convertToJSON(time_in_force_2); + printf("repeating time_in_force:\n%s\n", cJSON_Print(jsontime_in_force_2)); +} + +int main() { + test_time_in_force(1); + test_time_in_force(0); + + printf("Hello world \n"); + return 0; +} + +#endif // time_in_force_MAIN +#endif // time_in_force_TEST diff --git a/ems-cloud-mgmt-sdk/c/unit-test/test_validation_error.c b/ems-cloud-mgmt-sdk/c/unit-test/test_validation_error.c new file mode 100644 index 0000000000..9c8a626cbc --- /dev/null +++ b/ems-cloud-mgmt-sdk/c/unit-test/test_validation_error.c @@ -0,0 +1,66 @@ +#ifndef validation_error_TEST +#define validation_error_TEST + +// the following is to include only the main from the first c file +#ifndef TEST_MAIN +#define TEST_MAIN +#define validation_error_MAIN +#endif // TEST_MAIN + +#include +#include +#include +#include +#include "../external/cJSON.h" + +#include "../model/validation_error.h" +validation_error_t* instantiate_validation_error(int include_optional); + + + +validation_error_t* instantiate_validation_error(int include_optional) { + validation_error_t* validation_error = NULL; + if (include_optional) { + validation_error = validation_error_create( + "https://tools.ietf.org/html/rfc7231#section-6.5.1", + "One or more validation errors occurred.", + 400, + "d200e8b5-4271a5461ce5342f", + "0" + ); + } else { + validation_error = validation_error_create( + "https://tools.ietf.org/html/rfc7231#section-6.5.1", + "One or more validation errors occurred.", + 400, + "d200e8b5-4271a5461ce5342f", + "0" + ); + } + + return validation_error; +} + + +#ifdef validation_error_MAIN + +void test_validation_error(int include_optional) { + validation_error_t* validation_error_1 = instantiate_validation_error(include_optional); + + cJSON* jsonvalidation_error_1 = validation_error_convertToJSON(validation_error_1); + printf("validation_error :\n%s\n", cJSON_Print(jsonvalidation_error_1)); + validation_error_t* validation_error_2 = validation_error_parseFromJSON(jsonvalidation_error_1); + cJSON* jsonvalidation_error_2 = validation_error_convertToJSON(validation_error_2); + printf("repeating validation_error:\n%s\n", cJSON_Print(jsonvalidation_error_2)); +} + +int main() { + test_validation_error(1); + test_validation_error(0); + + printf("Hello world \n"); + return 0; +} + +#endif // validation_error_MAIN +#endif // validation_error_TEST diff --git a/ems-cloud-mgmt-sdk/clojure/.gitignore b/ems-cloud-mgmt-sdk/clojure/.gitignore new file mode 100644 index 0000000000..47fed6c20d --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/.gitignore @@ -0,0 +1,12 @@ +pom.xml +pom.xml.asc +*jar +/lib/ +/classes/ +/target/ +/checkouts/ +.lein-deps-sum +.lein-repl-history +.lein-plugins/ +.lein-failures +.nrepl-port diff --git a/ems-cloud-mgmt-sdk/clojure/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/clojure/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/clojure/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/clojure/.openapi-generator/FILES new file mode 100644 index 0000000000..302afd2b1a --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/.openapi-generator/FILES @@ -0,0 +1,25 @@ +.gitignore +.openapi-generator-ignore +git_push.sh +project.clj +src/ems_rest_api/api/balances.clj +src/ems_rest_api/api/orders.clj +src/ems_rest_api/api/positions.clj +src/ems_rest_api/core.clj +src/ems_rest_api/specs/balance.clj +src/ems_rest_api/specs/balance_data.clj +src/ems_rest_api/specs/fills.clj +src/ems_rest_api/specs/message_reject.clj +src/ems_rest_api/specs/ord_side.clj +src/ems_rest_api/specs/ord_status.clj +src/ems_rest_api/specs/ord_type.clj +src/ems_rest_api/specs/order_cancel_all_request.clj +src/ems_rest_api/specs/order_cancel_single_request.clj +src/ems_rest_api/specs/order_execution_report.clj +src/ems_rest_api/specs/order_execution_report_all_of.clj +src/ems_rest_api/specs/order_new_single_request.clj +src/ems_rest_api/specs/position.clj +src/ems_rest_api/specs/position_data.clj +src/ems_rest_api/specs/reject_reason.clj +src/ems_rest_api/specs/time_in_force.clj +src/ems_rest_api/specs/validation_error.clj diff --git a/ems-cloud-mgmt-sdk/clojure/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/clojure/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/clojure/git_push.sh b/ems-cloud-mgmt-sdk/clojure/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/ems-cloud-mgmt-sdk/clojure/project.clj b/ems-cloud-mgmt-sdk/clojure/project.clj new file mode 100644 index 0000000000..bbb2347d7f --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/project.clj @@ -0,0 +1,73 @@ +(defproject ems-rest-api "v1" + :description "This section will provide necessary information about the `CoinAPI EMS REST API` protocol. +
+This API is also available in the Postman application: https://postman.coinapi.io/ +

+Implemented Standards: + + * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) + * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) + * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) + +### Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
+ +### Authentication +If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. +

+If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: + + 1. Custom authorization header named `X-CoinAPI-Key` with the API Key + 2. Query string parameter named `apikey` with the API Key + 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. + +#### Custom authorization header +You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. +Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like: +

+`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` + +#### Query string authorization parameter +You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. +Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: +

+`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` +" + :url "https://www.coinapi.io" + :license {:name "28961" + :url "https://github.com/coinapi/coinapi-sdk/blob/master/LICENSE"} + :dependencies [[org.clojure/clojure "1.9.0"] + [metosin/spec-tools "0.7.0"] + [clj-http "3.8.0"] + [orchestra "2017.11.12-1"] + [cheshire "5.8.0"]]) \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/balances.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/balances.clj new file mode 100644 index 0000000000..4b27fc2eec --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/balances.clj @@ -0,0 +1,51 @@ +(ns ems-rest-api.api.balances + (:require [ems-rest-api.core :refer [call-api check-required-params with-collection-format *api-context*]] + [clojure.spec.alpha :as s] + [spec-tools.core :as st] + [orchestra.core :refer [defn-spec]] + [ems-rest-api.specs.time-in-force :refer :all] + [ems-rest-api.specs.balance-data :refer :all] + [ems-rest-api.specs.validation-error :refer :all] + [ems-rest-api.specs.reject-reason :refer :all] + [ems-rest-api.specs.position-data :refer :all] + [ems-rest-api.specs.order-cancel-single-request :refer :all] + [ems-rest-api.specs.ord-status :refer :all] + [ems-rest-api.specs.order-execution-report-all-of :refer :all] + [ems-rest-api.specs.balance :refer :all] + [ems-rest-api.specs.ord-type :refer :all] + [ems-rest-api.specs.order-execution-report :refer :all] + [ems-rest-api.specs.message-reject :refer :all] + [ems-rest-api.specs.order-cancel-all-request :refer :all] + [ems-rest-api.specs.position :refer :all] + [ems-rest-api.specs.order-new-single-request :refer :all] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs.fills :refer :all] + ) + (:import (java.io File))) + + +(defn-spec v1-balances-get-with-http-info any? + "Get balances + Get current currency balance from all or single exchange." + ([] (v1-balances-get-with-http-info nil)) + ([{:keys [exchange_id]} (s/map-of keyword? any?)] + (call-api "/v1/balances" :get + {:path-params {} + :header-params {} + :query-params {"exchange_id" exchange_id } + :form-params {} + :content-types [] + :accepts ["application/json" "appliction/json"] + :auth-names []}))) + +(defn-spec v1-balances-get (s/coll-of balance-spec) + "Get balances + Get current currency balance from all or single exchange." + ([] (v1-balances-get nil)) + ([optional-params any?] + (let [res (:data (v1-balances-get-with-http-info optional-params))] + (if (:decode-models *api-context*) + (st/decode (s/coll-of balance-spec) res st/string-transformer) + res)))) + + diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/orders.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/orders.clj new file mode 100644 index 0000000000..5e725eb063 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/orders.clj @@ -0,0 +1,150 @@ +(ns ems-rest-api.api.orders + (:require [ems-rest-api.core :refer [call-api check-required-params with-collection-format *api-context*]] + [clojure.spec.alpha :as s] + [spec-tools.core :as st] + [orchestra.core :refer [defn-spec]] + [ems-rest-api.specs.time-in-force :refer :all] + [ems-rest-api.specs.balance-data :refer :all] + [ems-rest-api.specs.validation-error :refer :all] + [ems-rest-api.specs.reject-reason :refer :all] + [ems-rest-api.specs.position-data :refer :all] + [ems-rest-api.specs.order-cancel-single-request :refer :all] + [ems-rest-api.specs.ord-status :refer :all] + [ems-rest-api.specs.order-execution-report-all-of :refer :all] + [ems-rest-api.specs.balance :refer :all] + [ems-rest-api.specs.ord-type :refer :all] + [ems-rest-api.specs.order-execution-report :refer :all] + [ems-rest-api.specs.message-reject :refer :all] + [ems-rest-api.specs.order-cancel-all-request :refer :all] + [ems-rest-api.specs.position :refer :all] + [ems-rest-api.specs.order-new-single-request :refer :all] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs.fills :refer :all] + ) + (:import (java.io File))) + + +(defn-spec v1-orders-cancel-all-post-with-http-info any? + "Cancel all orders request + This request cancels all open orders on single specified exchange." + [order-cancel-all-request order-cancel-all-request] + (check-required-params order-cancel-all-request) + (call-api "/v1/orders/cancel/all" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param order-cancel-all-request + :content-types ["application/json"] + :accepts ["application/json" "appliction/json"] + :auth-names []})) + +(defn-spec v1-orders-cancel-all-post message-reject-spec + "Cancel all orders request + This request cancels all open orders on single specified exchange." + [order-cancel-all-request order-cancel-all-request] + (let [res (:data (v1-orders-cancel-all-post-with-http-info order-cancel-all-request))] + (if (:decode-models *api-context*) + (st/decode message-reject-spec res st/string-transformer) + res))) + + +(defn-spec v1-orders-cancel-post-with-http-info any? + "Cancel order request + Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`." + [order-cancel-single-request order-cancel-single-request] + (check-required-params order-cancel-single-request) + (call-api "/v1/orders/cancel" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param order-cancel-single-request + :content-types ["application/json"] + :accepts ["application/json" "appliction/json"] + :auth-names []})) + +(defn-spec v1-orders-cancel-post order-execution-report-spec + "Cancel order request + Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`." + [order-cancel-single-request order-cancel-single-request] + (let [res (:data (v1-orders-cancel-post-with-http-info order-cancel-single-request))] + (if (:decode-models *api-context*) + (st/decode order-execution-report-spec res st/string-transformer) + res))) + + +(defn-spec v1-orders-get-with-http-info any? + "Get open orders + Get last execution reports for open orders across all or single exchange." + ([] (v1-orders-get-with-http-info nil)) + ([{:keys [exchange_id]} (s/map-of keyword? any?)] + (call-api "/v1/orders" :get + {:path-params {} + :header-params {} + :query-params {"exchange_id" exchange_id } + :form-params {} + :content-types [] + :accepts ["application/json" "appliction/json"] + :auth-names []}))) + +(defn-spec v1-orders-get (s/coll-of order-execution-report-spec) + "Get open orders + Get last execution reports for open orders across all or single exchange." + ([] (v1-orders-get nil)) + ([optional-params any?] + (let [res (:data (v1-orders-get-with-http-info optional-params))] + (if (:decode-models *api-context*) + (st/decode (s/coll-of order-execution-report-spec) res st/string-transformer) + res)))) + + +(defn-spec v1-orders-post-with-http-info any? + "Send new order + This request creating new order for the specific exchange." + [order-new-single-request order-new-single-request] + (check-required-params order-new-single-request) + (call-api "/v1/orders" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param order-new-single-request + :content-types ["application/json"] + :accepts ["application/json" "appliction/json"] + :auth-names []})) + +(defn-spec v1-orders-post order-execution-report-spec + "Send new order + This request creating new order for the specific exchange." + [order-new-single-request order-new-single-request] + (let [res (:data (v1-orders-post-with-http-info order-new-single-request))] + (if (:decode-models *api-context*) + (st/decode order-execution-report-spec res st/string-transformer) + res))) + + +(defn-spec v1-orders-status-client-order-id-get-with-http-info any? + "Get order execution report + Get the last order execution report for the specified order. The requested order does not need to be active or opened." + [client_order_id string?] + (check-required-params client_order_id) + (call-api "/v1/orders/status/{client_order_id}" :get + {:path-params {"client_order_id" client_order_id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json"] + :auth-names []})) + +(defn-spec v1-orders-status-client-order-id-get order-execution-report-spec + "Get order execution report + Get the last order execution report for the specified order. The requested order does not need to be active or opened." + [client_order_id string?] + (let [res (:data (v1-orders-status-client-order-id-get-with-http-info client_order_id))] + (if (:decode-models *api-context*) + (st/decode order-execution-report-spec res st/string-transformer) + res))) + + diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/positions.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/positions.clj new file mode 100644 index 0000000000..d45b104ca5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/api/positions.clj @@ -0,0 +1,51 @@ +(ns ems-rest-api.api.positions + (:require [ems-rest-api.core :refer [call-api check-required-params with-collection-format *api-context*]] + [clojure.spec.alpha :as s] + [spec-tools.core :as st] + [orchestra.core :refer [defn-spec]] + [ems-rest-api.specs.time-in-force :refer :all] + [ems-rest-api.specs.balance-data :refer :all] + [ems-rest-api.specs.validation-error :refer :all] + [ems-rest-api.specs.reject-reason :refer :all] + [ems-rest-api.specs.position-data :refer :all] + [ems-rest-api.specs.order-cancel-single-request :refer :all] + [ems-rest-api.specs.ord-status :refer :all] + [ems-rest-api.specs.order-execution-report-all-of :refer :all] + [ems-rest-api.specs.balance :refer :all] + [ems-rest-api.specs.ord-type :refer :all] + [ems-rest-api.specs.order-execution-report :refer :all] + [ems-rest-api.specs.message-reject :refer :all] + [ems-rest-api.specs.order-cancel-all-request :refer :all] + [ems-rest-api.specs.position :refer :all] + [ems-rest-api.specs.order-new-single-request :refer :all] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs.fills :refer :all] + ) + (:import (java.io File))) + + +(defn-spec v1-positions-get-with-http-info any? + "Get open positions + Get current open positions across all or single exchange." + ([] (v1-positions-get-with-http-info nil)) + ([{:keys [exchange_id]} (s/map-of keyword? any?)] + (call-api "/v1/positions" :get + {:path-params {} + :header-params {} + :query-params {"exchange_id" exchange_id } + :form-params {} + :content-types [] + :accepts ["application/json" "appliction/json"] + :auth-names []}))) + +(defn-spec v1-positions-get (s/coll-of position-spec) + "Get open positions + Get current open positions across all or single exchange." + ([] (v1-positions-get nil)) + ([optional-params any?] + (let [res (:data (v1-positions-get-with-http-info optional-params))] + (if (:decode-models *api-context*) + (st/decode (s/coll-of position-spec) res st/string-transformer) + res)))) + + diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/core.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/core.clj new file mode 100644 index 0000000000..797dc2a5b7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/core.clj @@ -0,0 +1,253 @@ +(ns ems-rest-api.core + (:require [cheshire.core :refer [generate-string parse-string]] + [clojure.string :as str] + [clj-http.client :as client]) + (:import (com.fasterxml.jackson.core JsonParseException) + (java.io File) + (java.util Date TimeZone) + (java.text SimpleDateFormat))) + +(def auth-definitions + {}) + +(def default-api-context + "Default API context." + {:base-url "https://ems-gateway-aws-eu-central-1-dev.coinapi.io" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :decode-models false + :debug false + :auths {}}) + +(def ^:dynamic *api-context* + "Dynamic API context to be applied in API calls." + default-api-context) + +(defn set-api-context + "Set the *api-context* globally" + [new-context] + (alter-var-root #'*api-context* (constantly (merge *api-context* new-context)))) + +(defmacro with-api-context + "A helper macro to wrap *api-context* with default values." + [api-context & body] + `(let [api-context# ~api-context + api-context# (-> *api-context* + (merge api-context#) + (assoc :auths (merge (:auths *api-context*) (:auths api-context#))))] + (binding [*api-context* api-context#] + ~@body))) + +(defmacro check-required-params + "Throw exception if any of the given parameters is nil." + [& params] + (->> params + (map (fn [p] + `(if (nil? ~p) + (throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required")))))) + (list* 'do))) + +(defn with-collection-format + "Attach collection-format to meta data of the given parameter." + [param collection-format] + (and param (with-meta param {:collection-format collection-format}))) + +(defn- ^SimpleDateFormat make-date-format + ([^String format-str] (make-date-format format-str nil)) + ([^String format-str ^String time-zone] + (let [date-format (SimpleDateFormat. format-str)] + (when time-zone + (.setTimeZone date-format (TimeZone/getTimeZone time-zone))) + date-format))) + +(defn format-date + "Format the given Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^Date date] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.format date)))) + +(defn parse-date + "Parse the given string to a Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^String s] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.parse s)))) + +(defn format-datetime + "Format the given Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^Date date] (format-datetime date nil)) + ([^Date date ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.format date))))) + +(defn parse-datetime + "Parse the given string to a Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^String s] (parse-datetime s nil)) + ([^String s ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.parse s))))) + +(defn param->str + "Format the given parameter value to string." + [param] + (cond + (instance? Date param) (format-datetime param) + (sequential? param) (str/join "," param) + :else (str param))) + +(defn auth->opts + "Process the given auth to an option map that might contain request options and parameters." + [{:keys [type in param-name]} value] + (case type + :basic {:req-opts {:basic-auth value}} + :oauth2 {:req-opts {:oauth-token value}} + :api-key (case in + :header {:header-params {param-name value}} + :query {:query-params {param-name value}} + (throw (IllegalArgumentException. (str "Invalid `in` for api-key auth: " in)))) + (throw (IllegalArgumentException. (str "Invalid auth `type`: " type))))) + +(defn process-auth + "Process the given auth name into options, which is merged into the given opts." + [opts auth-name] + (if-let [value (get-in *api-context* [:auths auth-name])] + (merge-with merge + opts + (auth->opts (get auth-definitions auth-name) value)) + opts)) + +(defn auths->opts + "Process the given auth names to an option map that might contain request options and parameters." + [auth-names] + (reduce process-auth {} auth-names)) + +(declare normalize-param) + +(defn make-url + "Make full URL by adding base URL and filling path parameters." + [path path-params] + (let [path (reduce (fn [p [k v]] + (str/replace p (re-pattern (str "\\{" k "\\}")) (normalize-param v))) + path + path-params)] + (str (:base-url *api-context*) path))) + +(defn normalize-array-param + "Normalize array parameter according to :collection-format specified in the parameter's meta data. + When the parameter contains File, a seq is returned so as to keep File parameters. + For :multi collection format, a seq is returned which will be handled properly by clj-http. + For other cases, a string is returned." + [xs] + (if (some (partial instance? File) xs) + (map normalize-param xs) + (case (-> (meta xs) :collection-format (or :csv)) + :csv (str/join "," (map normalize-param xs)) + :ssv (str/join " " (map normalize-param xs)) + :tsv (str/join "\t" (map normalize-param xs)) + :pipes (str/join "|" (map normalize-param xs)) + :multi (map normalize-param xs)))) + +(defn normalize-param + "Normalize parameter value, handling three cases: + for sequential value, apply `normalize-array-param` which handles collection format; + for File value, use current value; + otherwise, apply `param->str`." + [param] + (cond + (sequential? param) (normalize-array-param param) + (instance? File param) param + :else (param->str param))) + +(defn normalize-params + "Normalize parameters values: remove nils, format to string with `param->str`." + [params] + (->> params + (remove (comp nil? second)) + (map (fn [[k v]] [k (normalize-param v)])) + (into {}))) + +(defn default-to-json-mime + "Default to JSON MIME if given */* MIME" + [mime] + (if (= mime "*/*") + "application/json" + mime)) + +(defn json-mime? + "Check if the given MIME is a standard JSON MIME or :json." + [mime] + (if mime + (or (= :json mime) + (re-matches #"(?i)application/json(;.*)?" (name mime))))) + +(defn json-preferred-mime + "Choose a MIME from the given MIMEs with JSON preferred, + i.e. return JSON if included, otherwise return the first one." + [mimes] + (-> (filter json-mime? mimes) + first + (or (default-to-json-mime (first mimes))))) + +(defn serialize + "Serialize the given data according to content-type. + Only JSON is supported for now." + [data content-type] + (if (json-mime? content-type) + (generate-string data {:date-format (:datetime-format *api-context*)}) + (throw (IllegalArgumentException. (str "Content type \"" content-type "\" is not support for serialization"))))) + +(defn deserialize + "Deserialize the given HTTP response according to the Content-Type header." + [{:keys [body] {:keys [content-type]} :headers}] + (cond + (json-mime? content-type) + (try + (parse-string body true) + (catch JsonParseException e + ;; Return the body string directly on JSON parsing error. + body)) + + ;; For other cases, return the body string directly. + :else body)) + +(defn form-params->multipart + "Convert the given form parameters map into a vector as clj-http's :multipart option." + [form-params] + (->> form-params + (map (fn [[k v]] (array-map :name k :content v))) + vec)) + +(defn call-api + "Call an API by making HTTP request and return its response." + [path method {:keys [path-params body-param content-types accepts auth-names] :as opts}] + (let [{:keys [debug]} *api-context* + {:keys [req-opts query-params header-params form-params]} (auths->opts auth-names) + query-params (merge query-params (:query-params opts)) + header-params (merge header-params (:header-params opts)) + form-params (merge form-params (:form-params opts)) + url (make-url path path-params) + content-type (or (json-preferred-mime content-types) (and body-param :json)) + accept (or (json-preferred-mime accepts) :json) + multipart? (= "multipart/form-data" content-type) + req-opts (cond-> req-opts + true (assoc :url url :method method) + accept (assoc :accept accept) + (seq query-params) (assoc :query-params (normalize-params query-params)) + (seq header-params) (assoc :headers (normalize-params header-params)) + (and content-type (not multipart?)) (assoc :content-type content-type) + multipart? (assoc :multipart (-> form-params normalize-params form-params->multipart)) + (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) + body-param (assoc :body (serialize body-param content-type)) + debug (assoc :debug true :debug-body true)) + resp (client/request req-opts)] + (when debug + (println "Response:") + (println resp)) + (assoc resp :data (deserialize resp)))) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance.clj new file mode 100644 index 0000000000..4a6e6bc18d --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance.clj @@ -0,0 +1,18 @@ +(ns ems-rest-api.specs.balance + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.balance-data :refer :all] + ) + (:import (java.io File))) + + +(def balance-data + { + (ds/opt :exchange_id) string? + (ds/opt :data) (s/coll-of balance-data-spec) + }) + +(def balance-spec + (ds/spec + {:name ::balance + :spec balance-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance_data.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance_data.clj new file mode 100644 index 0000000000..a4c6e812ee --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/balance_data.clj @@ -0,0 +1,23 @@ +(ns ems-rest-api.specs.balance-data + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def balance-data-data + { + (ds/opt :asset_id_exchange) string? + (ds/opt :asset_id_coinapi) string? + (ds/opt :balance) float? + (ds/opt :available) float? + (ds/opt :locked) float? + (ds/opt :last_updated_by) string? + (ds/opt :rate_usd) float? + (ds/opt :traded) float? + }) + +(def balance-data-spec + (ds/spec + {:name ::balance-data + :spec balance-data-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/fills.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/fills.clj new file mode 100644 index 0000000000..94c7effacf --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/fills.clj @@ -0,0 +1,18 @@ +(ns ems-rest-api.specs.fills + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def fills-data + { + (ds/opt :time) inst? + (ds/opt :price) float? + (ds/opt :amount) float? + }) + +(def fills-spec + (ds/spec + {:name ::fills + :spec fills-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/message_reject.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/message_reject.clj new file mode 100644 index 0000000000..6405024d6f --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/message_reject.clj @@ -0,0 +1,21 @@ +(ns ems-rest-api.specs.message-reject + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.reject-reason :refer :all] + ) + (:import (java.io File))) + + +(def message-reject-data + { + (ds/opt :type) string? + (ds/opt :reject_reason) reject-reason-spec + (ds/opt :exchange_id) string? + (ds/opt :message) string? + (ds/opt :rejected_message) string? + }) + +(def message-reject-spec + (ds/spec + {:name ::message-reject + :spec message-reject-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_side.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_side.clj new file mode 100644 index 0000000000..fbdced7cbe --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_side.clj @@ -0,0 +1,15 @@ +(ns ems-rest-api.specs.ord-side + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def ord-side-data + { + }) + +(def ord-side-spec + (ds/spec + {:name ::ord-side + :spec ord-side-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_status.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_status.clj new file mode 100644 index 0000000000..6e0ebda170 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_status.clj @@ -0,0 +1,15 @@ +(ns ems-rest-api.specs.ord-status + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def ord-status-data + { + }) + +(def ord-status-spec + (ds/spec + {:name ::ord-status + :spec ord-status-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_type.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_type.clj new file mode 100644 index 0000000000..6775fdc497 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/ord_type.clj @@ -0,0 +1,15 @@ +(ns ems-rest-api.specs.ord-type + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def ord-type-data + { + }) + +(def ord-type-spec + (ds/spec + {:name ::ord-type + :spec ord-type-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_all_request.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_all_request.clj new file mode 100644 index 0000000000..96c5e65bf5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_all_request.clj @@ -0,0 +1,16 @@ +(ns ems-rest-api.specs.order-cancel-all-request + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def order-cancel-all-request-data + { + (ds/req :exchange_id) string? + }) + +(def order-cancel-all-request-spec + (ds/spec + {:name ::order-cancel-all-request + :spec order-cancel-all-request-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_single_request.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_single_request.clj new file mode 100644 index 0000000000..903949bffa --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_cancel_single_request.clj @@ -0,0 +1,18 @@ +(ns ems-rest-api.specs.order-cancel-single-request + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def order-cancel-single-request-data + { + (ds/req :exchange_id) string? + (ds/opt :exchange_order_id) string? + (ds/opt :client_order_id) string? + }) + +(def order-cancel-single-request-spec + (ds/spec + {:name ::order-cancel-single-request + :spec order-cancel-single-request-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report.clj new file mode 100644 index 0000000000..da5f914411 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report.clj @@ -0,0 +1,40 @@ +(ns ems-rest-api.specs.order-execution-report + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs.ord-type :refer :all] + [ems-rest-api.specs.time-in-force :refer :all] + [ems-rest-api.specs.ord-status :refer :all] + [ems-rest-api.specs.fills :refer :all] + ) + (:import (java.io File))) + + +(def order-execution-report-data + { + (ds/req :exchange_id) string? + (ds/req :client_order_id) string? + (ds/opt :symbol_id_exchange) string? + (ds/opt :symbol_id_coinapi) string? + (ds/req :amount_order) float? + (ds/req :price) float? + (ds/req :side) ord-side-spec + (ds/req :order_type) ord-type-spec + (ds/req :time_in_force) time-in-force-spec + (ds/opt :expire_time) inst? + (ds/opt :exec_inst) (s/coll-of string?) + (ds/req :client_order_id_format_exchange) string? + (ds/opt :exchange_order_id) string? + (ds/req :amount_open) float? + (ds/req :amount_filled) float? + (ds/opt :avg_px) float? + (ds/req :status) ord-status-spec + (ds/opt :status_history) (s/coll-of (s/coll-of string?)) + (ds/opt :error_message) string? + (ds/opt :fills) (s/coll-of fills-spec) + }) + +(def order-execution-report-spec + (ds/spec + {:name ::order-execution-report + :spec order-execution-report-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report_all_of.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report_all_of.clj new file mode 100644 index 0000000000..3e7d1b88d7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_execution_report_all_of.clj @@ -0,0 +1,26 @@ +(ns ems-rest-api.specs.order-execution-report-all-of + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.ord-status :refer :all] + [ems-rest-api.specs.fills :refer :all] + ) + (:import (java.io File))) + + +(def order-execution-report-all-of-data + { + (ds/req :client_order_id_format_exchange) string? + (ds/opt :exchange_order_id) string? + (ds/req :amount_open) float? + (ds/req :amount_filled) float? + (ds/opt :avg_px) float? + (ds/req :status) ord-status-spec + (ds/opt :status_history) (s/coll-of (s/coll-of string?)) + (ds/opt :error_message) string? + (ds/opt :fills) (s/coll-of fills-spec) + }) + +(def order-execution-report-all-of-spec + (ds/spec + {:name ::order-execution-report-all-of + :spec order-execution-report-all-of-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_new_single_request.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_new_single_request.clj new file mode 100644 index 0000000000..4ac6f08f81 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/order_new_single_request.clj @@ -0,0 +1,29 @@ +(ns ems-rest-api.specs.order-new-single-request + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs.ord-type :refer :all] + [ems-rest-api.specs.time-in-force :refer :all] + ) + (:import (java.io File))) + + +(def order-new-single-request-data + { + (ds/req :exchange_id) string? + (ds/req :client_order_id) string? + (ds/opt :symbol_id_exchange) string? + (ds/opt :symbol_id_coinapi) string? + (ds/req :amount_order) float? + (ds/req :price) float? + (ds/req :side) ord-side-spec + (ds/req :order_type) ord-type-spec + (ds/req :time_in_force) time-in-force-spec + (ds/opt :expire_time) inst? + (ds/opt :exec_inst) (s/coll-of string?) + }) + +(def order-new-single-request-spec + (ds/spec + {:name ::order-new-single-request + :spec order-new-single-request-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position.clj new file mode 100644 index 0000000000..9175b1e3d0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position.clj @@ -0,0 +1,18 @@ +(ns ems-rest-api.specs.position + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.position-data :refer :all] + ) + (:import (java.io File))) + + +(def position-data + { + (ds/opt :exchange_id) string? + (ds/opt :data) (s/coll-of position-data-spec) + }) + +(def position-spec + (ds/spec + {:name ::position + :spec position-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position_data.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position_data.clj new file mode 100644 index 0000000000..da4f174d0f --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/position_data.clj @@ -0,0 +1,27 @@ +(ns ems-rest-api.specs.position-data + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + [ems-rest-api.specs.ord-side :refer :all] + [ems-rest-api.specs. :refer :all] + ) + (:import (java.io File))) + + +(def position-data-data + { + (ds/opt :symbol_id_exchange) string? + (ds/opt :symbol_id_coinapi) string? + (ds/opt :avg_entry_price) float? + (ds/opt :quantity) float? + (ds/opt :side) ord-side-spec + (ds/opt :unrealized_pnl) float? + (ds/opt :leverage) float? + (ds/opt :cross_margin) boolean? + (ds/opt :liquidation_price) float? + (ds/opt :raw_data) any? + }) + +(def position-data-spec + (ds/spec + {:name ::position-data + :spec position-data-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/reject_reason.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/reject_reason.clj new file mode 100644 index 0000000000..4f99de07ae --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/reject_reason.clj @@ -0,0 +1,15 @@ +(ns ems-rest-api.specs.reject-reason + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def reject-reason-data + { + }) + +(def reject-reason-spec + (ds/spec + {:name ::reject-reason + :spec reject-reason-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/time_in_force.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/time_in_force.clj new file mode 100644 index 0000000000..60f055f6a3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/time_in_force.clj @@ -0,0 +1,15 @@ +(ns ems-rest-api.specs.time-in-force + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def time-in-force-data + { + }) + +(def time-in-force-spec + (ds/spec + {:name ::time-in-force + :spec time-in-force-data})) diff --git a/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/validation_error.clj b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/validation_error.clj new file mode 100644 index 0000000000..16cff29c35 --- /dev/null +++ b/ems-cloud-mgmt-sdk/clojure/src/ems_rest_api/specs/validation_error.clj @@ -0,0 +1,20 @@ +(ns ems-rest-api.specs.validation-error + (:require [clojure.spec.alpha :as s] + [spec-tools.data-spec :as ds] + ) + (:import (java.io File))) + + +(def validation-error-data + { + (ds/opt :type) string? + (ds/opt :title) string? + (ds/opt :status) float? + (ds/opt :traceId) string? + (ds/opt :errors) string? + }) + +(def validation-error-spec + (ds/spec + {:name ::validation-error + :spec validation-error-data})) diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/.gitignore b/ems-cloud-mgmt-sdk/cpp-restsdk/.gitignore new file mode 100644 index 0000000000..4581ef2eee --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/.gitignore @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/FILES new file mode 100644 index 0000000000..6dc197b52d --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/FILES @@ -0,0 +1,63 @@ +.gitignore +.openapi-generator-ignore +ApiClient.cpp +ApiClient.h +ApiConfiguration.cpp +ApiConfiguration.h +ApiException.cpp +ApiException.h +CMakeLists.txt +Config.cmake.in +HttpContent.cpp +HttpContent.h +IHttpBody.h +JsonBody.cpp +JsonBody.h +ModelBase.cpp +ModelBase.h +MultipartFormData.cpp +MultipartFormData.h +Object.cpp +Object.h +README.md +api/BalancesApi.cpp +api/BalancesApi.h +api/OrdersApi.cpp +api/OrdersApi.h +api/PositionsApi.cpp +api/PositionsApi.h +git_push.sh +model/Balance.cpp +model/Balance.h +model/Balance_data.cpp +model/Balance_data.h +model/Fills.cpp +model/Fills.h +model/MessageReject.cpp +model/MessageReject.h +model/OrdSide.cpp +model/OrdSide.h +model/OrdStatus.cpp +model/OrdStatus.h +model/OrdType.cpp +model/OrdType.h +model/OrderCancelAllRequest.cpp +model/OrderCancelAllRequest.h +model/OrderCancelSingleRequest.cpp +model/OrderCancelSingleRequest.h +model/OrderExecutionReport.cpp +model/OrderExecutionReport.h +model/OrderExecutionReport_allOf.cpp +model/OrderExecutionReport_allOf.h +model/OrderNewSingleRequest.cpp +model/OrderNewSingleRequest.h +model/Position.cpp +model/Position.h +model/Position_data.cpp +model/Position_data.h +model/RejectReason.cpp +model/RejectReason.h +model/TimeInForce.cpp +model/TimeInForce.h +model/ValidationError.cpp +model/ValidationError.h diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.cpp new file mode 100644 index 0000000000..ca5fa4d879 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.cpp @@ -0,0 +1,209 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "ApiClient.h" +#include "MultipartFormData.h" +#include "ModelBase.h" + +#include +#include +#include + +template +utility::string_t toString(const T value) +{ + utility::ostringstream_t out; + out << std::setprecision(std::numeric_limits::digits10) << std::fixed << value; + return out.str(); +} + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +ApiClient::ApiClient(std::shared_ptr configuration ) + : m_Configuration(configuration) +{ +} +ApiClient::~ApiClient() +{ +} + +const ApiClient::ResponseHandlerType& ApiClient::getResponseHandler() const { + return m_ResponseHandler; +} + +void ApiClient::setResponseHandler(const ResponseHandlerType& responseHandler) { + m_ResponseHandler = responseHandler; +} + +std::shared_ptr ApiClient::getConfiguration() const +{ + return m_Configuration; +} +void ApiClient::setConfiguration(std::shared_ptr configuration) +{ + m_Configuration = configuration; +} + + +utility::string_t ApiClient::parameterToString(utility::string_t value) +{ + return value; +} +utility::string_t ApiClient::parameterToString(int64_t value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} +utility::string_t ApiClient::parameterToString(int32_t value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} + +utility::string_t ApiClient::parameterToString(float value) +{ + return utility::conversions::to_string_t(toString(value)); +} + +utility::string_t ApiClient::parameterToString(double value) +{ + return utility::conversions::to_string_t(toString(value)); +} + +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + +utility::string_t ApiClient::parameterToString(bool value) +{ + std::stringstream valueAsStringStream; + valueAsStringStream << std::boolalpha << value; + return utility::conversions::to_string_t(valueAsStringStream.str()); +} + +pplx::task ApiClient::callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType +) const +{ + if (postBody != nullptr && formParams.size() != 0) + { + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params")); + } + + if (postBody != nullptr && fileParams.size() != 0) + { + throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params")); + } + + if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data")) + { + throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data")); + } + + web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); + + web::http::http_request request; + for (const auto& kvp : headerParams) + { + request.headers().add(kvp.first, kvp.second); + } + + if (fileParams.size() > 0) + { + MultipartFormData uploadData; + for (const auto& kvp : formParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + for (const auto& kvp : fileParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + std::stringstream data; + uploadData.writeTo(data); + auto bodyString = data.str(); + const auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary()); + } + else + { + if (postBody != nullptr) + { + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + const auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + if (contentType == utility::conversions::to_string_t("application/json")) + { + web::json::value body_data = web::json::value::object(); + for (auto& kvp : formParams) + { + body_data[kvp.first] = ModelBase::toJson(kvp.second); + } + if (!formParams.empty()) + { + request.set_body(body_data); + } + } + else + { + web::http::uri_builder formData; + for (const auto& kvp : formParams) + { + formData.append_query(kvp.first, kvp.second); + } + if (!formParams.empty()) + { + request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded")); + } + } + } + } + + web::http::uri_builder builder(path); + for (const auto& kvp : queryParams) + { + builder.append_query(kvp.first, kvp.second); + } + request.set_request_uri(builder.to_uri()); + request.set_method(method); + if ( !request.headers().has( web::http::header_names::user_agent ) ) + { + request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); + } + + return client.request(request); +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.h b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.h new file mode 100644 index 0000000000..d742d0cba3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiClient.h @@ -0,0 +1,115 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiClient.h + * + * This is an API client responsible for stating the HTTP calls + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ + + +#include "ApiConfiguration.h" +#include "ApiException.h" +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include +#include + +#if defined (_WIN32) || defined (_WIN64) +#undef U +#endif + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +class ApiClient +{ +public: + ApiClient( std::shared_ptr configuration = nullptr ); + virtual ~ApiClient(); + + typedef std::function ResponseHandlerType; + + const ResponseHandlerType& getResponseHandler() const; + void setResponseHandler(const ResponseHandlerType& responseHandler); + + std::shared_ptr getConfiguration() const; + void setConfiguration(std::shared_ptr configuration); + + static utility::string_t parameterToString(utility::string_t value); + static utility::string_t parameterToString(int32_t value); + static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(float value); + static utility::string_t parameterToString(double value); + static utility::string_t parameterToString(const utility::datetime &value); + static utility::string_t parameterToString(bool value); + template + static utility::string_t parameterToString(const std::vector& value); + template + static utility::string_t parameterToString(const std::shared_ptr& value); + + pplx::task callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, + const std::map>& fileParams, + const utility::string_t& contentType + ) const; + +protected: + + ResponseHandlerType m_ResponseHandler; + std::shared_ptr m_Configuration; +}; + +template +utility::string_t ApiClient::parameterToString(const std::vector& value) +{ + utility::stringstream_t ss; + + for( size_t i = 0; i < value.size(); i++) + { + if( i > 0) ss << utility::conversions::to_string_t(", "); + ss << ApiClient::parameterToString(value[i]); + } + + return ss.str(); +} + +template +utility::string_t ApiClient::parameterToString(const std::shared_ptr& value) +{ + return parameterToString(*value.get()); +} + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiClient_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.cpp new file mode 100644 index 0000000000..90727f43de --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.cpp @@ -0,0 +1,86 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "ApiConfiguration.h" + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +ApiConfiguration::ApiConfiguration() +{ +} + +ApiConfiguration::~ApiConfiguration() +{ +} + +const web::http::client::http_client_config& ApiConfiguration::getHttpConfig() const +{ + return m_HttpConfig; +} + +void ApiConfiguration::setHttpConfig( web::http::client::http_client_config& value ) +{ + m_HttpConfig = value; +} + +utility::string_t ApiConfiguration::getBaseUrl() const +{ + return m_BaseUrl; +} + +void ApiConfiguration::setBaseUrl( const utility::string_t value ) +{ + m_BaseUrl = value; +} + +utility::string_t ApiConfiguration::getUserAgent() const +{ + return m_UserAgent; +} + +void ApiConfiguration::setUserAgent( const utility::string_t value ) +{ + m_UserAgent = value; +} + +std::map& ApiConfiguration::getDefaultHeaders() +{ + return m_DefaultHeaders; +} + +const std::map& ApiConfiguration::getDefaultHeaders() const +{ + return m_DefaultHeaders; +} + +utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) const +{ + auto result = m_ApiKeys.find(prefix); + if( result != m_ApiKeys.end() ) + { + return result->second; + } + return utility::conversions::to_string_t(""); +} + +void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ) +{ + m_ApiKeys[prefix] = apiKey; +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.h b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.h new file mode 100644 index 0000000000..265f60df7b --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiConfiguration.h @@ -0,0 +1,66 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiConfiguration.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ + + + +#include + +#include +#include +namespace org { +namespace openapitools { +namespace client { +namespace api { + +class ApiConfiguration +{ +public: + ApiConfiguration(); + virtual ~ApiConfiguration(); + + const web::http::client::http_client_config& getHttpConfig() const; + void setHttpConfig( web::http::client::http_client_config& value ); + + utility::string_t getBaseUrl() const; + void setBaseUrl( const utility::string_t value ); + + utility::string_t getUserAgent() const; + void setUserAgent( const utility::string_t value ); + + std::map& getDefaultHeaders(); + const std::map& getDefaultHeaders() const; + + utility::string_t getApiKey( const utility::string_t& prefix) const; + void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ); + +protected: + utility::string_t m_BaseUrl; + std::map m_DefaultHeaders; + std::map m_ApiKeys; + web::http::client::http_client_config m_HttpConfig; + utility::string_t m_UserAgent; +}; + +} +} +} +} +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiConfiguration_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.cpp new file mode 100644 index 0000000000..b3942129a2 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.cpp @@ -0,0 +1,54 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "ApiException.h" + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) +{ +} +ApiException::ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content /*= nullptr*/ ) + : web::http::http_exception( errorCode, message ) + , m_Content(content) + , m_Headers(headers) +{ +} + +ApiException::~ApiException() +{ +} + +std::shared_ptr ApiException::getContent() const +{ + return m_Content; +} + +std::map& ApiException::getHeaders() +{ + return m_Headers; +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.h b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.h new file mode 100644 index 0000000000..d24138783e --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ApiException.h @@ -0,0 +1,62 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiException.h + * + * This is the exception being thrown in case the api call was not successful + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_ApiException_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_ApiException_H_ + + + +#include +#include + +#include +#include + + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +class ApiException + : public web::http::http_exception +{ +public: + ApiException( int errorCode + , const utility::string_t& message + , std::shared_ptr content = nullptr ); + ApiException( int errorCode + , const utility::string_t& message + , std::map& headers + , std::shared_ptr content = nullptr ); + virtual ~ApiException(); + + std::map& getHeaders(); + std::shared_ptr getContent() const; + +protected: + std::shared_ptr m_Content; + std::map m_Headers; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_ApiBase_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/CMakeLists.txt b/ems-cloud-mgmt-sdk/cpp-restsdk/CMakeLists.txt new file mode 100644 index 0000000000..2db5f0ccc6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/CMakeLists.txt @@ -0,0 +1,92 @@ +# +# EMS - REST API +# This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` +# +# The version of the OpenAPI document: 1.0.0 +# +# https://openapi-generator.tech +# +# NOTE: Auto generated by OpenAPI Generator (https://openapi-generator.tech). + +cmake_minimum_required (VERSION 3.1) + +project(CppRestOpenAPIClient) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(CXX_STANDARD_REQUIRED ON) + +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 14) +endif() + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +find_package(cpprestsdk REQUIRED) +find_package(Boost REQUIRED) + +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +file(GLOB_RECURSE HEADER_FILES "*.h") +file(GLOB_RECURSE SOURCE_FILES "*.cpp") + +add_library(${PROJECT_NAME} ${HEADER_FILES} ${SOURCE_FILES}) + +target_compile_options(${PROJECT_NAME} + PRIVATE + $<$,$,$>: + -Wall -Wno-unused-variable> +) + +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ +) + +target_link_directories(${PROJECT_NAME} + PRIVATE + ${Boost_LIBRARY_DIRS} +) + +if (UNIX) + message(STATUS "Building client library for Linux/Unix") + + target_link_libraries(${PROJECT_NAME} PUBLIC cpprest ${Boost_LIBRARIES} crypto) +else() + message(STATUS "Building client library for Windows") + + target_link_libraries(${PROJECT_NAME} PUBLIC cpprestsdk::cpprest ${Boost_LIBRARIES} bcrypt) +endif() + +configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" +) + +install( + TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" +) + +install( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + FILES_MATCHING PATTERN "*.h" +) + +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +install( + EXPORT ${PROJECT_NAME}Targets + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/Config.cmake.in b/ems-cloud-mgmt-sdk/cpp-restsdk/Config.cmake.in new file mode 100644 index 0000000000..2a485225c0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/Config.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake) + +check_required_components("@PROJECT_NAME@") diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.cpp new file mode 100644 index 0000000000..f4249da087 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.cpp @@ -0,0 +1,87 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "HttpContent.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +HttpContent::HttpContent() +{ +} + +HttpContent::~HttpContent() +{ +} + +utility::string_t HttpContent::getContentDisposition() const +{ + return m_ContentDisposition; +} + +void HttpContent::setContentDisposition( const utility::string_t & value ) +{ + m_ContentDisposition = value; +} + +utility::string_t HttpContent::getName() const +{ + return m_Name; +} + +void HttpContent::setName( const utility::string_t & value ) +{ + m_Name = value; +} + +utility::string_t HttpContent::getFileName() const +{ + return m_FileName; +} + +void HttpContent::setFileName( const utility::string_t & value ) +{ + m_FileName = value; +} + +utility::string_t HttpContent::getContentType() const +{ + return m_ContentType; +} + +void HttpContent::setContentType( const utility::string_t & value ) +{ + m_ContentType = value; +} + +std::shared_ptr HttpContent::getData() const +{ + return m_Data; +} + +void HttpContent::setData( std::shared_ptr value ) +{ + m_Data = value; +} + +void HttpContent::writeTo( std::ostream& stream ) +{ + m_Data->seekg( 0, m_Data->beg ); + stream << m_Data->rdbuf(); +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.h b/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.h new file mode 100644 index 0000000000..8d21ec0e9e --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/HttpContent.h @@ -0,0 +1,70 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * HttpContent.h + * + * This class represents a single item of a multipart-formdata request. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ + + + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class HttpContent +{ +public: + HttpContent(); + virtual ~HttpContent(); + + virtual utility::string_t getContentDisposition() const; + virtual void setContentDisposition( const utility::string_t& value ); + + virtual utility::string_t getName() const; + virtual void setName( const utility::string_t& value ); + + virtual utility::string_t getFileName() const; + virtual void setFileName( const utility::string_t& value ); + + virtual utility::string_t getContentType() const; + virtual void setContentType( const utility::string_t& value ); + + virtual std::shared_ptr getData() const; + virtual void setData( std::shared_ptr value ); + + virtual void writeTo( std::ostream& stream ); + +protected: + // NOTE: no utility::string_t here because those strings can only contain ascii + utility::string_t m_ContentDisposition; + utility::string_t m_Name; + utility::string_t m_FileName; + utility::string_t m_ContentType; + std::shared_ptr m_Data; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_HttpContent_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/IHttpBody.h b/ems-cloud-mgmt-sdk/cpp-restsdk/IHttpBody.h new file mode 100644 index 0000000000..e387472b38 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/IHttpBody.h @@ -0,0 +1,43 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * IHttpBody.h + * + * This is the interface for contents that can be sent to a remote HTTP server. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ + + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class IHttpBody +{ +public: + virtual ~IHttpBody() { } + + virtual void writeTo( std::ostream& stream ) = 0; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_IHttpBody_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.cpp new file mode 100644 index 0000000000..b93e1241b7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.cpp @@ -0,0 +1,37 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "JsonBody.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +JsonBody::JsonBody( const web::json::value& json) + : m_Json(json) +{ +} + +JsonBody::~JsonBody() +{ +} + +void JsonBody::writeTo( std::ostream& target ) +{ + m_Json.serialize(target); +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.h b/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.h new file mode 100644 index 0000000000..65b2698838 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/JsonBody.h @@ -0,0 +1,50 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * JsonBody.h + * + * This is a JSON http body which can be submitted via http + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ + + +#include "IHttpBody.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class JsonBody + : public IHttpBody +{ +public: + JsonBody( const web::json::value& value ); + virtual ~JsonBody(); + + void writeTo( std::ostream& target ) override; + +protected: + web::json::value m_Json; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_JsonBody_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.cpp new file mode 100644 index 0000000000..3ccae313d7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.cpp @@ -0,0 +1,619 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "ModelBase.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +ModelBase::ModelBase(): m_IsSet(false) +{ +} +ModelBase::~ModelBase() +{ +} +bool ModelBase::isSet() const +{ + return m_IsSet; +} +utility::string_t ModelBase::toString( const bool val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const float val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const double val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const int32_t val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const int64_t val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString (const utility::string_t &val ) +{ + utility::stringstream_t ss; + ss << val; + return utility::string_t(ss.str()); +} +utility::string_t ModelBase::toString( const utility::datetime &val ) +{ + return val.to_string(utility::datetime::ISO_8601); +} +utility::string_t ModelBase::toString( const web::json::value &val ) +{ + return val.serialize(); +} +utility::string_t ModelBase::toString( const std::shared_ptr& val ) +{ + utility::stringstream_t ss; + if( val != nullptr ) + { + ss << val->getData(); + } + return utility::string_t(ss.str()); +} +web::json::value ModelBase::toJson(bool value) +{ + return web::json::value::boolean(value); +} +web::json::value ModelBase::toJson( float value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( double value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( int32_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( int64_t value ) +{ + return web::json::value::number(value); +} +web::json::value ModelBase::toJson( const utility::string_t& value ) +{ + return web::json::value::string(value); +} +web::json::value ModelBase::toJson( const utility::datetime& value ) +{ + return web::json::value::string(value.to_string(utility::datetime::ISO_8601)); +} +web::json::value ModelBase::toJson( const web::json::value& value ) +{ + return value; +} +web::json::value ModelBase::toJson( const std::shared_ptr& content ) +{ + web::json::value value; + if(content != nullptr) + { + value[utility::conversions::to_string_t("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition()); + value[utility::conversions::to_string_t("ContentType")] = ModelBase::toJson(content->getContentType()); + value[utility::conversions::to_string_t("FileName")] = ModelBase::toJson(content->getFileName()); + value[utility::conversions::to_string_t("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) ); + } + return value; +} +bool ModelBase::fromString( const utility::string_t& val, bool &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, float &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + int64_t intVal = 0; + success = ModelBase::fromString(val, intVal); + if(success) + { + outVal = static_cast(intVal); + } + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, double &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + int64_t intVal = 0; + success = ModelBase::fromString(val, intVal); + if(success) + { + outVal = static_cast(intVal); + } + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, int32_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, int64_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, utility::string_t &outVal ) +{ + utility::stringstream_t ss(val); + bool success = true; + try + { + ss >> outVal; + } + catch (...) + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, utility::datetime &outVal ) +{ + bool success = true; + auto dt = utility::datetime::from_string(val, utility::datetime::ISO_8601); + if( dt.is_initialized() ) + { + outVal = dt; + } + else + { + success = false; + } + return success; +} +bool ModelBase::fromString( const utility::string_t& val, web::json::value &outVal ) +{ + outVal = web::json::value::parse(val); + return !outVal.is_null(); +} +bool ModelBase::fromString( const utility::string_t& val, std::shared_ptr& outVal ) +{ + bool ok = true; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new HttpContent()); + } + if(outVal != nullptr) + { + outVal->setData(std::shared_ptr(new std::stringstream(utility::conversions::to_utf8string(val)))); + } + else + { + ok = false; + } + return ok; +} +bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) +{ + outVal = !val.is_boolean() ? false : val.as_bool(); + return val.is_boolean(); +} +bool ModelBase::fromJson( const web::json::value& val, float & outVal ) +{ + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, double & outVal ) +{ + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) +{ + outVal = !val.is_integer() ? std::numeric_limits::quiet_NaN() : val.as_integer(); + return val.is_integer(); +} +bool ModelBase::fromJson( const web::json::value& val, int64_t & outVal ) +{ + outVal = !val.is_number() ? std::numeric_limits::quiet_NaN() : val.as_number().to_int64(); + return val.is_number(); +} +bool ModelBase::fromJson( const web::json::value& val, utility::string_t & outVal ) +{ + outVal = val.is_string() ? val.as_string() : utility::conversions::to_string_t(""); + return val.is_string(); +} +bool ModelBase::fromJson( const web::json::value& val, utility::datetime & outVal ) +{ + outVal = val.is_null() ? utility::datetime::from_string(utility::conversions::to_string_t("NULL"), utility::datetime::ISO_8601) : utility::datetime::from_string(val.as_string(), utility::datetime::ISO_8601); + return outVal.is_initialized(); +} +bool ModelBase::fromJson( const web::json::value& val, web::json::value & outVal ) +{ + outVal = val; + return !val.is_null(); +} +bool ModelBase::fromJson( const web::json::value& val, std::shared_ptr& content ) +{ + bool result = false; + if( content != nullptr) + { + result = true; + if(content == nullptr) + { + content = std::shared_ptr(new HttpContent()); + } + if(val.has_field(utility::conversions::to_string_t("ContentDisposition"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("ContentDisposition")), value); + content->setContentDisposition( value ); + } + if(val.has_field(utility::conversions::to_string_t("ContentType"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("ContentType")), value); + content->setContentType( value ); + } + if(val.has_field(utility::conversions::to_string_t("FileName"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("FileName")), value); + content->setFileName( value ); + } + if(val.has_field(utility::conversions::to_string_t("InputStream"))) + { + utility::string_t value; + result = result && ModelBase::fromJson(val.at(utility::conversions::to_string_t("InputStream")), value); + content->setData( ModelBase::fromBase64( value ) ); + } + } + return result; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, bool value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, float value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + std::stringstream* valueAsStringStream = new std::stringstream(); + (*valueAsStringStream) << value; + content->setData( std::shared_ptr( valueAsStringStream) ) ; + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType) +{ + std::shared_ptr content(new HttpContent); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) ); + return content; +} +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::shared_ptr& value ) +{ + std::shared_ptr content( new HttpContent ); + if( value != nullptr ) + { + content->setName( name ); + content->setContentDisposition( value->getContentDisposition() ); + content->setContentType( value->getContentType() ); + content->setData( value->getData() ); + content->setFileName( value->getFileName() ); + } + return content; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, bool & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, float & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, double & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, int32_t & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, int64_t & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, utility::string_t & outVal ) +{ + if( val == nullptr ) return false; + std::shared_ptr data = val->getData(); + data->seekg( 0, data->beg ); + + std::string str((std::istreambuf_iterator(*data.get())), + std::istreambuf_iterator()); + outVal = utility::conversions::to_string_t(str); + return true; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, utility::datetime & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + outVal = utility::datetime::from_string(str, utility::datetime::ISO_8601); + return true; +} +bool ModelBase::fromHttpContent(std::shared_ptr val, web::json::value & outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +bool ModelBase::fromHttpContent(std::shared_ptr val, std::shared_ptr& outVal ) +{ + utility::string_t str; + if( val == nullptr ) return false; + if( outVal == nullptr ) + { + outVal = std::shared_ptr(new HttpContent()); + } + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +// base64 encoding/decoding based on : https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64#C.2B.2B +const static char Base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const static char Base64PadChar = '='; +utility::string_t ModelBase::toBase64( utility::string_t value ) +{ + std::shared_ptr source( new std::stringstream( utility::conversions::to_utf8string(value) ) ); + return ModelBase::toBase64(source); +} +utility::string_t ModelBase::toBase64( std::shared_ptr value ) +{ + value->seekg( 0, value->end ); + size_t length = value->tellg(); + value->seekg( 0, value->beg ); + utility::string_t base64; + base64.reserve( ((length / 3) + (length % 3 > 0)) * 4 ); + char read[3] = { 0 }; + uint32_t temp; + for ( size_t idx = 0; idx < length / 3; idx++ ) + { + value->read( read, 3 ); + temp = (read[0]) << 16; + temp += (read[1]) << 8; + temp += (read[2]); + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64Chars[(temp & 0x0000003F)] ); + } + switch ( length % 3 ) + { + case 1: + value->read( read, 1 ); + temp = read[0] << 16; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 2, Base64PadChar ); + break; + case 2: + value->read( read, 2 ); + temp = read[0] << 16; + temp += read[1] << 8; + base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); + base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); + base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] ); + base64.append( 1, Base64PadChar ); + break; + } + return base64; +} +std::shared_ptr ModelBase::fromBase64( const utility::string_t& encoded ) +{ + std::shared_ptr result(new std::stringstream); + + char outBuf[3] = { 0 }; + uint32_t temp = 0; + + utility::string_t::const_iterator cursor = encoded.begin(); + while ( cursor < encoded.end() ) + { + for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ ) + { + temp <<= 6; + if ( *cursor >= 0x41 && *cursor <= 0x5A ) + { + temp |= *cursor - 0x41; + } + else if ( *cursor >= 0x61 && *cursor <= 0x7A ) + { + temp |= *cursor - 0x47; + } + else if ( *cursor >= 0x30 && *cursor <= 0x39 ) + { + temp |= *cursor + 0x04; + } + else if ( *cursor == 0x2B ) + { + temp |= 0x3E; //change to 0x2D for URL alphabet + } + else if ( *cursor == 0x2F ) + { + temp |= 0x3F; //change to 0x5F for URL alphabet + } + else if ( *cursor == Base64PadChar ) //pad + { + switch ( encoded.end() - cursor ) + { + case 1: //One pad character + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + result->write( outBuf, 2 ); + return result; + case 2: //Two pad characters + outBuf[0] = (temp >> 10) & 0x000000FF; + result->write( outBuf, 1 ); + return result; + default: + throw web::json::json_exception( utility::conversions::to_string_t( "Invalid Padding in Base 64!" ).c_str() ); + } + } + else + { + throw web::json::json_exception( utility::conversions::to_string_t( "Non-Valid Character in Base 64!" ).c_str() ); + } + ++cursor; + } + + outBuf[0] = (temp >> 16) & 0x000000FF; + outBuf[1] = (temp >> 8) & 0x000000FF; + outBuf[2] = (temp) & 0x000000FF; + result->write( outBuf, 3 ); + } + + return result; +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.h b/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.h new file mode 100644 index 0000000000..fc1e8a5267 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/ModelBase.h @@ -0,0 +1,338 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ModelBase.h + * + * This is the base class for all model classes + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ + + +#include +#include + +#include "HttpContent.h" +#include "MultipartFormData.h" + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class ModelBase +{ +public: + ModelBase(); + virtual ~ModelBase(); + + virtual void validate() = 0; + + virtual web::json::value toJson() const = 0; + virtual bool fromJson( const web::json::value& json ) = 0; + + virtual void toMultipart( std::shared_ptr multipart, const utility::string_t& namePrefix ) const = 0; + virtual bool fromMultiPart( std::shared_ptr multipart, const utility::string_t& namePrefix ) = 0; + + virtual bool isSet() const; + + static utility::string_t toString( const bool val ); + static utility::string_t toString( const float val ); + static utility::string_t toString( const double val ); + static utility::string_t toString( const int32_t val ); + static utility::string_t toString( const int64_t val ); + static utility::string_t toString( const utility::string_t &val ); + static utility::string_t toString( const utility::datetime &val ); + static utility::string_t toString( const web::json::value &val ); + static utility::string_t toString( const std::shared_ptr& val ); + template + static utility::string_t toString( const std::shared_ptr& val ); + template + static utility::string_t toString( const std::vector & val ); + + static web::json::value toJson( bool val ); + static web::json::value toJson( float val ); + static web::json::value toJson( double val ); + static web::json::value toJson( int32_t val ); + static web::json::value toJson( int64_t val ); + static web::json::value toJson( const utility::string_t& val ); + static web::json::value toJson( const utility::datetime& val ); + static web::json::value toJson( const web::json::value& val ); + static web::json::value toJson( const std::shared_ptr& val ); + template + static web::json::value toJson( const std::shared_ptr& val ); + template + static web::json::value toJson( const std::vector& val ); + template + static web::json::value toJson( const std::map& val ); + + static bool fromString( const utility::string_t& val, bool & ); + static bool fromString( const utility::string_t& val, float & ); + static bool fromString( const utility::string_t& val, double & ); + static bool fromString( const utility::string_t& val, int32_t & ); + static bool fromString( const utility::string_t& val, int64_t & ); + static bool fromString( const utility::string_t& val, utility::string_t & ); + static bool fromString( const utility::string_t& val, utility::datetime & ); + static bool fromString( const utility::string_t& val, web::json::value & ); + static bool fromString( const utility::string_t& val, std::shared_ptr & ); + template + static bool fromString( const utility::string_t& val, std::shared_ptr& ); + template + static bool fromString( const utility::string_t& val, std::vector & ); + template + static bool fromString( const utility::string_t& val, std::map & ); + + static bool fromJson( const web::json::value& val, bool & ); + static bool fromJson( const web::json::value& val, float & ); + static bool fromJson( const web::json::value& val, double & ); + static bool fromJson( const web::json::value& val, int32_t & ); + static bool fromJson( const web::json::value& val, int64_t & ); + static bool fromJson( const web::json::value& val, utility::string_t & ); + static bool fromJson( const web::json::value& val, utility::datetime & ); + static bool fromJson( const web::json::value& val, web::json::value & ); + static bool fromJson( const web::json::value& val, std::shared_ptr & ); + template + static bool fromJson( const web::json::value& val, std::shared_ptr& ); + template + static bool fromJson( const web::json::value& val, std::vector & ); + template + static bool fromJson( const web::json::value& val, std::map & ); + + + static std::shared_ptr toHttpContent( const utility::string_t& name, bool value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, float value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = utility::conversions::to_string_t("")); + static std::shared_ptr toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::shared_ptr& ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::shared_ptr& , const utility::string_t& contentType = utility::conversions::to_string_t("application/json") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + template + static std::shared_ptr toHttpContent( const utility::string_t& name, const std::map& value, const utility::string_t& contentType = utility::conversions::to_string_t("") ); + + static bool fromHttpContent( std::shared_ptr val, bool & ); + static bool fromHttpContent( std::shared_ptr val, float & ); + static bool fromHttpContent( std::shared_ptr val, double & ); + static bool fromHttpContent( std::shared_ptr val, int64_t & ); + static bool fromHttpContent( std::shared_ptr val, int32_t & ); + static bool fromHttpContent( std::shared_ptr val, utility::string_t & ); + static bool fromHttpContent( std::shared_ptr val, utility::datetime & ); + static bool fromHttpContent( std::shared_ptr val, web::json::value & ); + static bool fromHttpContent( std::shared_ptr val, std::shared_ptr& ); + template + static bool fromHttpContent( std::shared_ptr val, std::shared_ptr& ); + template + static bool fromHttpContent( std::shared_ptr val, std::vector & ); + template + static bool fromHttpContent( std::shared_ptr val, std::map & ); + + static utility::string_t toBase64( utility::string_t value ); + static utility::string_t toBase64( std::shared_ptr value ); + static std::shared_ptr fromBase64( const utility::string_t& encoded ); +protected: + bool m_IsSet; +}; + +template +utility::string_t ModelBase::toString( const std::shared_ptr& val ) +{ + utility::stringstream_t ss; + if( val != nullptr ) + { + val->toJson().serialize(ss); + } + return utility::string_t(ss.str()); +} +template +utility::string_t ModelBase::toString( const std::vector & val ) +{ + utility::string_t strArray; + for ( const auto &item : val ) + { + strArray.append( toString(item) + "," ); + } + if (val.count() > 0) + { + strArray.pop_back(); + } + return strArray; +} +template +web::json::value ModelBase::toJson( const std::shared_ptr& val ) +{ + web::json::value retVal; + if(val != nullptr) + { + retVal = val->toJson(); + } + return retVal; +} +template +web::json::value ModelBase::toJson( const std::vector& value ) +{ + std::vector ret; + for ( const auto& x : value ) + { + ret.push_back( toJson(x) ); + } + return web::json::value::array(ret); +} +template +web::json::value ModelBase::toJson( const std::map& val ) +{ + web::json::value obj; + for ( const auto &itemkey : val ) + { + obj[itemkey.first] = toJson( itemkey.second ); + } + return obj; +} +template +bool ModelBase::fromString( const utility::string_t& val, std::shared_ptr& outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new T()); + } + if( outVal != nullptr ) + { + ok = outVal->fromJson(web::json::value::parse(val)); + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& val, std::shared_ptr &outVal ) +{ + bool ok = false; + if(outVal == nullptr) + { + outVal = std::shared_ptr(new T()); + } + if( outVal != nullptr ) + { + ok = outVal->fromJson(val); + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& val, std::vector &outVal ) +{ + bool ok = true; + if (val.is_array()) + { + for (const auto jitem : val.as_array()) + { + T item; + ok &= fromJson(jitem, item); + outVal.push_back(item); + } + } + else + { + ok = false; + } + return ok; +} +template +bool ModelBase::fromJson( const web::json::value& jval, std::map &outVal ) +{ + bool ok = true; + if ( jval.is_object() ) + { + auto obj = jval.as_object(); + for( auto objItr = obj.begin() ; objItr != obj.end() ; objItr++ ) + { + T itemVal; + ok &= fromJson(objItr->second, itemVal); + outVal.insert(std::pair(objItr->first, itemVal)); + } + } + else + { + ok = false; + } + return ok; +} +template +std::shared_ptr ModelBase::toHttpContent(const utility::string_t& name, const std::shared_ptr& value , const utility::string_t& contentType ) +{ + std::shared_ptr content( new HttpContent ); + if (value != nullptr ) + { + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string( value->toJson().serialize() ) ) ) ); + } + return content; +} +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::vector& value, const utility::string_t& contentType ) +{ + web::json::value json_array = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(json_array.serialize()) ) ) ); + return content; +} +template +std::shared_ptr ModelBase::toHttpContent( const utility::string_t& name, const std::map& value, const utility::string_t& contentType ) +{ + web::json::value jobj = ModelBase::toJson(value); + std::shared_ptr content( new HttpContent ); + content->setName( name ); + content->setContentDisposition( utility::conversions::to_string_t("form-data") ); + content->setContentType( contentType ); + content->setData( std::shared_ptr( new std::stringstream( utility::conversions::to_utf8string(jobj.serialize()) ) ) ); + return content; +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::shared_ptr& outVal ) +{ + utility::string_t str; + if(val == nullptr) return false; + if( outVal == nullptr ) + { + outVal = std::shared_ptr(new T()); + } + ModelBase::fromHttpContent(val, str); + return fromString(str, outVal); +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::vector & ) +{ + return true; +} +template +bool ModelBase::fromHttpContent( std::shared_ptr val, std::map & ) +{ + return true; +} +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ModelBase_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.cpp new file mode 100644 index 0000000000..9222a7d726 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.cpp @@ -0,0 +1,113 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "MultipartFormData.h" +#include "ModelBase.h" + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +MultipartFormData::MultipartFormData() +{ + utility::stringstream_t uuidString; + uuidString << boost::uuids::random_generator()(); + m_Boundary = uuidString.str(); +} + +MultipartFormData::MultipartFormData(const utility::string_t& boundary) + : m_Boundary(boundary) +{ + +} + +MultipartFormData::~MultipartFormData() +{ +} + +utility::string_t MultipartFormData::getBoundary() +{ + return m_Boundary; +} + +void MultipartFormData::add( std::shared_ptr content ) +{ + m_Contents.push_back( content ); + m_ContentLookup[content->getName()] = content; +} + +bool MultipartFormData::hasContent(const utility::string_t& name) const +{ + return m_ContentLookup.find(name) != m_ContentLookup.end(); +} + +std::shared_ptr MultipartFormData::getContent(const utility::string_t& name) const +{ + auto result = m_ContentLookup.find(name); + if(result == m_ContentLookup.end()) + { + return std::shared_ptr(nullptr); + } + return result->second; +} + +void MultipartFormData::writeTo( std::ostream& target ) +{ + for ( size_t i = 0; i < m_Contents.size(); i++ ) + { + std::shared_ptr content = m_Contents[i]; + + // boundary + target << "\r\n" << "--" << utility::conversions::to_utf8string( m_Boundary ) << "\r\n"; + + // headers + target << "Content-Disposition: " << utility::conversions::to_utf8string( content->getContentDisposition() ); + if ( content->getName().size() > 0 ) + { + target << "; name=\"" << utility::conversions::to_utf8string( content->getName() ) << "\""; + } + if ( content->getFileName().size() > 0 ) + { + target << "; filename=\"" << utility::conversions::to_utf8string( content->getFileName() ) << "\""; + } + target << "\r\n"; + + if ( content->getContentType().size() > 0 ) + { + target << "Content-Type: " << utility::conversions::to_utf8string( content->getContentType() ) << "\r\n"; + } + + target << "\r\n"; + + // body + std::shared_ptr data = content->getData(); + + data->seekg( 0, data->end ); + std::vector dataBytes( data->tellg() ); + + data->seekg( 0, data->beg ); + data->read( &dataBytes[0], dataBytes.size() ); + + std::copy( dataBytes.begin(), dataBytes.end(), std::ostreambuf_iterator( target ) ); + } + + target << "\r\n--" << utility::conversions::to_utf8string( m_Boundary ) << "--\r\n"; +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.h b/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.h new file mode 100644 index 0000000000..6310caa787 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/MultipartFormData.h @@ -0,0 +1,63 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * MultipartFormData.h + * + * This class represents a container for building application/x-multipart-formdata requests. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ + + +#include "IHttpBody.h" +#include "HttpContent.h" + +#include +#include +#include + +#include + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class MultipartFormData + : public IHttpBody +{ +public: + MultipartFormData(); + MultipartFormData(const utility::string_t& boundary); + virtual ~MultipartFormData(); + + virtual void add( std::shared_ptr content ); + virtual utility::string_t getBoundary(); + virtual std::shared_ptr getContent(const utility::string_t& name) const; + virtual bool hasContent(const utility::string_t& name) const; + virtual void writeTo( std::ostream& target ); + +protected: + std::vector> m_Contents; + utility::string_t m_Boundary; + std::map> m_ContentLookup; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/Object.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/Object.cpp new file mode 100644 index 0000000000..9e1c7de61f --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/Object.cpp @@ -0,0 +1,92 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "Object.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +Object::Object() +{ + m_object = web::json::value::object(); +} + +Object::~Object() +{ +} + +void Object::validate() +{ + +} + +web::json::value Object::toJson() const +{ + return m_object; +} + +bool Object::fromJson(const web::json::value& val) +{ + if (val.is_object()) + { + m_object = val; + m_IsSet = true; + } + return isSet(); +} + +void Object::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) + { + namePrefix += utility::conversions::to_string_t("."); + } + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("object"), m_object)); +} + +bool Object::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) + { + namePrefix += utility::conversions::to_string_t("."); + } + + if( ModelBase::fromHttpContent(multipart->getContent(namePrefix + utility::conversions::to_string_t("object")), m_object ) ) + { + m_IsSet = true; + } + return isSet(); +} + +web::json::value Object::getValue(const utility::string_t& key) const +{ + return m_object.at(key); +} + + +void Object::setValue(const utility::string_t& key, const web::json::value& value) +{ + if( !value.is_null() ) + { + m_object[key] = value; + m_IsSet = true; + } +} + +} +} +} +} diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/Object.h b/ems-cloud-mgmt-sdk/cpp-restsdk/Object.h new file mode 100644 index 0000000000..86bd681187 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/Object.h @@ -0,0 +1,63 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Object.h + * + * This is the implementation of a JSON object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ + + +#include "ModelBase.h" + +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class Object : public ModelBase +{ +public: + Object(); + virtual ~Object(); + + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Object manipulation + web::json::value getValue(const utility::string_t& key) const; + void setValue(const utility::string_t& key, const web::json::value& value); + +private: + web::json::value m_object; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Object_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/README.md b/ems-cloud-mgmt-sdk/cpp-restsdk/README.md new file mode 100644 index 0000000000..113ddced62 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/README.md @@ -0,0 +1,115 @@ +# C++ API client + +This section will provide necessary information about the `CoinAPI EMS REST API` protocol. +
+This API is also available in the Postman application: https://postman.coinapi.io/ +

+Implemented Standards: + + * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) + * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) + * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) + +### Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Deployment methodEnvironmentUrl
Managed CloudProductionUse Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed CloudSandboxhttps://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self HostedProductionIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self HostedSandboxIP Address of the ems-gateway container/excecutable in the closest server site to the caller location
+ +### Authentication +If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls. +

+If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: + + 1. Custom authorization header named `X-CoinAPI-Key` with the API Key + 2. Query string parameter named `apikey` with the API Key + 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. + +#### Custom authorization header +You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. +Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like: +

+`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` + +#### Query string authorization parameter +You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. +Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this: +

+`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + + + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: v1 +- Package version: +- Build package: org.openapitools.codegen.languages.CppRestSdkClientCodegen +For more information, please visit [https://www.coinapi.io](https://www.coinapi.io) + +- API namespace: org.openapitools.client.api +- Model namespace: org.openapitools.client.model + +## Installation + +### Prerequisites + +Install [cpprestsdk](https://github.com/Microsoft/cpprestsdk). + +- Windows: `vcpkg install cpprestsdk cpprestsdk:x64-windows boost-uuid boost-uuid:x64-windows` +- Mac: `brew install cpprestsdk` +- Linux: `sudo apt-get install libcpprest-dev` + +### Build + +```sh +cmake -DCPPREST_ROOT=/usr -DCMAKE_CXX_FLAGS="-I/usr/local/opt/openssl/include" -DCMAKE_MODULE_LINKER_FLAGS="-L/usr/local/opt/openssl/lib" +make +``` + +### Build on Windows with Visual Studio (VS2017) + +- Right click on folder containing source code +- Select 'Open in visual studio' +- Once visual studio opens, CMake should show up in top menu bar. +- Select CMake > Build All. + +*Note: If the CMake menu item doesn't show up in Visual Studio, CMake +for Visual Studio must be installed. In this case, open the 'Visual Studio +Installer' application. Select 'modify' Visual Studio 2017. Make sure +'Desktop Development with C++' is installed, and specifically that 'Visual +C++ tools for CMake' is selected in the 'Installation Details' section. + +Also be sure to review the CMakeLists.txt file. Edits are likely required.* + +## Author + +support@coinapi.io + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.cpp new file mode 100644 index 0000000000..fd0316a1e8 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.cpp @@ -0,0 +1,175 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "BalancesApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +BalancesApi::BalancesApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +BalancesApi::~BalancesApi() +{ +} + +pplx::task>> BalancesApi::v1BalancesGet(boost::optional exchangeId) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/balances"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("BalancesApi->v1BalancesGet does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + if (exchangeId) + { + localVarQueryParams[utility::conversions::to_string_t("exchange_id")] = ApiClient::parameterToString(*exchangeId); + } + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("BalancesApi->v1BalancesGet does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1BalancesGet: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1BalancesGet: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::vector> localVarResult; + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + for( auto& localVarItem : localVarJson.as_array() ) + { + std::shared_ptr localVarItemObj; + ModelBase::fromJson(localVarItem, localVarItemObj); + localVarResult.push_back(localVarItemObj); + } + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1BalancesGet: unsupported response type")); + } + + return localVarResult; + }); +} + +} +} +} +} + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.h b/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.h new file mode 100644 index 0000000000..0c46064b88 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/BalancesApi.h @@ -0,0 +1,69 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * BalancesApi.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_BalancesApi_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_BalancesApi_H_ + + + +#include "ApiClient.h" + +#include "model/Balance.h" +#include "model/MessageReject.h" +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + + + +class BalancesApi +{ +public: + + explicit BalancesApi( std::shared_ptr apiClient ); + + virtual ~BalancesApi(); + + /// + /// Get balances + /// + /// + /// Get current currency balance from all or single exchange. + /// + /// Filter the balances to the specific exchange. (optional, default to utility::conversions::to_string_t("")) + pplx::task>> v1BalancesGet( + boost::optional exchangeId + ) const; + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_BalancesApi_H_ */ + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.cpp new file mode 100644 index 0000000000..b7faf8b2b4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.cpp @@ -0,0 +1,736 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OrdersApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +OrdersApi::OrdersApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +OrdersApi::~OrdersApi() +{ +} + +pplx::task> OrdersApi::v1OrdersCancelAllPost(std::shared_ptr orderCancelAllRequest) const +{ + + // verify the required parameter 'orderCancelAllRequest' is set + if (orderCancelAllRequest == nullptr) + { + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'orderCancelAllRequest' when calling OrdersApi->v1OrdersCancelAllPost")); + } + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/orders/cancel/all"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("OrdersApi->v1OrdersCancelAllPost does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + web::json::value localVarJson; + + localVarJson = ModelBase::toJson(orderCancelAllRequest); + + + localVarHttpBody = std::shared_ptr( new JsonBody( localVarJson ) ); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + std::shared_ptr localVarMultipart(new MultipartFormData); + + if(orderCancelAllRequest.get()) + { + orderCancelAllRequest->toMultipart(localVarMultipart, utility::conversions::to_string_t("orderCancelAllRequest")); + } + + + localVarHttpBody = localVarMultipart; + localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary(); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("OrdersApi->v1OrdersCancelAllPost does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1OrdersCancelAllPost: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersCancelAllPost: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(new MessageReject()); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersCancelAllPost: unsupported response type")); + } + + return localVarResult; + }); +} +pplx::task> OrdersApi::v1OrdersCancelPost(std::shared_ptr orderCancelSingleRequest) const +{ + + // verify the required parameter 'orderCancelSingleRequest' is set + if (orderCancelSingleRequest == nullptr) + { + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'orderCancelSingleRequest' when calling OrdersApi->v1OrdersCancelPost")); + } + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/orders/cancel"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("OrdersApi->v1OrdersCancelPost does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + web::json::value localVarJson; + + localVarJson = ModelBase::toJson(orderCancelSingleRequest); + + + localVarHttpBody = std::shared_ptr( new JsonBody( localVarJson ) ); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + std::shared_ptr localVarMultipart(new MultipartFormData); + + if(orderCancelSingleRequest.get()) + { + orderCancelSingleRequest->toMultipart(localVarMultipart, utility::conversions::to_string_t("orderCancelSingleRequest")); + } + + + localVarHttpBody = localVarMultipart; + localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary(); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("OrdersApi->v1OrdersCancelPost does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1OrdersCancelPost: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersCancelPost: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(new OrderExecutionReport()); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersCancelPost: unsupported response type")); + } + + return localVarResult; + }); +} +pplx::task>> OrdersApi::v1OrdersGet(boost::optional exchangeId) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/orders"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("OrdersApi->v1OrdersGet does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + if (exchangeId) + { + localVarQueryParams[utility::conversions::to_string_t("exchange_id")] = ApiClient::parameterToString(*exchangeId); + } + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("OrdersApi->v1OrdersGet does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1OrdersGet: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersGet: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::vector> localVarResult; + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + for( auto& localVarItem : localVarJson.as_array() ) + { + std::shared_ptr localVarItemObj; + ModelBase::fromJson(localVarItem, localVarItemObj); + localVarResult.push_back(localVarItemObj); + } + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersGet: unsupported response type")); + } + + return localVarResult; + }); +} +pplx::task> OrdersApi::v1OrdersPost(std::shared_ptr orderNewSingleRequest) const +{ + + // verify the required parameter 'orderNewSingleRequest' is set + if (orderNewSingleRequest == nullptr) + { + throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'orderNewSingleRequest' when calling OrdersApi->v1OrdersPost")); + } + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/orders"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("OrdersApi->v1OrdersPost does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + web::json::value localVarJson; + + localVarJson = ModelBase::toJson(orderNewSingleRequest); + + + localVarHttpBody = std::shared_ptr( new JsonBody( localVarJson ) ); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + std::shared_ptr localVarMultipart(new MultipartFormData); + + if(orderNewSingleRequest.get()) + { + orderNewSingleRequest->toMultipart(localVarMultipart, utility::conversions::to_string_t("orderNewSingleRequest")); + } + + + localVarHttpBody = localVarMultipart; + localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary(); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("OrdersApi->v1OrdersPost does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1OrdersPost: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersPost: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(new OrderExecutionReport()); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersPost: unsupported response type")); + } + + return localVarResult; + }); +} +pplx::task> OrdersApi::v1OrdersStatusClientOrderIdGet(utility::string_t clientOrderId) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/orders/status/{client_order_id}"); + boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("client_order_id") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(clientOrderId)); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("OrdersApi->v1OrdersStatusClientOrderIdGet does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("OrdersApi->v1OrdersStatusClientOrderIdGet does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1OrdersStatusClientOrderIdGet: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersStatusClientOrderIdGet: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::shared_ptr localVarResult(new OrderExecutionReport()); + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + + ModelBase::fromJson(localVarJson, localVarResult); + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1OrdersStatusClientOrderIdGet: unsupported response type")); + } + + return localVarResult; + }); +} + +} +} +} +} + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.h b/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.h new file mode 100644 index 0000000000..d3552932e3 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/OrdersApi.h @@ -0,0 +1,113 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrdersApi.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_OrdersApi_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_OrdersApi_H_ + + + +#include "ApiClient.h" + +#include "model/MessageReject.h" +#include "model/OrderCancelAllRequest.h" +#include "model/OrderCancelSingleRequest.h" +#include "model/OrderExecutionReport.h" +#include "model/OrderNewSingleRequest.h" +#include "model/ValidationError.h" +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + + + +class OrdersApi +{ +public: + + explicit OrdersApi( std::shared_ptr apiClient ); + + virtual ~OrdersApi(); + + /// + /// Cancel all orders request + /// + /// + /// This request cancels all open orders on single specified exchange. + /// + /// OrderCancelAllRequest object. + pplx::task> v1OrdersCancelAllPost( + std::shared_ptr orderCancelAllRequest + ) const; + /// + /// Cancel order request + /// + /// + /// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`. + /// + /// OrderCancelSingleRequest object. + pplx::task> v1OrdersCancelPost( + std::shared_ptr orderCancelSingleRequest + ) const; + /// + /// Get open orders + /// + /// + /// Get last execution reports for open orders across all or single exchange. + /// + /// Filter the open orders to the specific exchange. (optional, default to utility::conversions::to_string_t("")) + pplx::task>> v1OrdersGet( + boost::optional exchangeId + ) const; + /// + /// Send new order + /// + /// + /// This request creating new order for the specific exchange. + /// + /// OrderNewSingleRequest object. + pplx::task> v1OrdersPost( + std::shared_ptr orderNewSingleRequest + ) const; + /// + /// Get order execution report + /// + /// + /// Get the last order execution report for the specified order. The requested order does not need to be active or opened. + /// + /// The unique identifier of the order assigned by the client. + pplx::task> v1OrdersStatusClientOrderIdGet( + utility::string_t clientOrderId + ) const; + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_OrdersApi_H_ */ + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.cpp new file mode 100644 index 0000000000..17a8ff0f1a --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.cpp @@ -0,0 +1,175 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "PositionsApi.h" +#include "IHttpBody.h" +#include "JsonBody.h" +#include "MultipartFormData.h" + +#include + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + +PositionsApi::PositionsApi( std::shared_ptr apiClient ) + : m_ApiClient(apiClient) +{ +} + +PositionsApi::~PositionsApi() +{ +} + +pplx::task>> PositionsApi::v1PositionsGet(boost::optional exchangeId) const +{ + + + std::shared_ptr localVarApiConfiguration( m_ApiClient->getConfiguration() ); + utility::string_t localVarPath = utility::conversions::to_string_t("/v1/positions"); + + std::map localVarQueryParams; + std::map localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() ); + std::map localVarFormParams; + std::map> localVarFileParams; + + std::unordered_set localVarResponseHttpContentTypes; + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); + localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("appliction/json") ); + + utility::string_t localVarResponseHttpContentType; + + // use JSON if possible + if ( localVarResponseHttpContentTypes.size() == 0 ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // JSON + else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() ) + { + localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else + { + throw ApiException(400, utility::conversions::to_string_t("PositionsApi->v1PositionsGet does not produce any supported media type")); + } + + localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType; + + std::unordered_set localVarConsumeHttpContentTypes; + + if (exchangeId) + { + localVarQueryParams[utility::conversions::to_string_t("exchange_id")] = ApiClient::parameterToString(*exchangeId); + } + + std::shared_ptr localVarHttpBody; + utility::string_t localVarRequestHttpContentType; + + // use JSON if possible + if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/json"); + } + // multipart formdata + else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() ) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); + } + else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end()) + { + localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded"); + } + else + { + throw ApiException(415, utility::conversions::to_string_t("PositionsApi->v1PositionsGet does not consume any supported media type")); + } + + + return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType) + .then([=](web::http::http_response localVarResponse) + { + if (m_ApiClient->getResponseHandler()) + { + m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers()); + } + + // 1xx - informational : OK + // 2xx - successful : OK + // 3xx - redirection : OK + // 4xx - client error : not OK + // 5xx - client error : not OK + if (localVarResponse.status_code() >= 400) + { + throw ApiException(localVarResponse.status_code() + , utility::conversions::to_string_t("error calling v1PositionsGet: ") + localVarResponse.reason_phrase() + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + + // check response content type + if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type"))) + { + utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")]; + if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos ) + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1PositionsGet: unexpected response type: ") + localVarContentType + , std::make_shared(localVarResponse.extract_utf8string(true).get())); + } + } + + return localVarResponse.extract_string(); + }) + .then([=](utility::string_t localVarResponse) + { + std::vector> localVarResult; + + if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json")) + { + web::json::value localVarJson = web::json::value::parse(localVarResponse); + for( auto& localVarItem : localVarJson.as_array() ) + { + std::shared_ptr localVarItemObj; + ModelBase::fromJson(localVarItem, localVarItemObj); + localVarResult.push_back(localVarItemObj); + } + } + // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , utility::conversions::to_string_t("error calling v1PositionsGet: unsupported response type")); + } + + return localVarResult; + }); +} + +} +} +} +} + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.h b/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.h new file mode 100644 index 0000000000..bf393404f5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/api/PositionsApi.h @@ -0,0 +1,69 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PositionsApi.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_API_PositionsApi_H_ +#define ORG_OPENAPITOOLS_CLIENT_API_PositionsApi_H_ + + + +#include "ApiClient.h" + +#include "model/MessageReject.h" +#include "model/Position.h" +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace api { + +using namespace org::openapitools::client::model; + + + +class PositionsApi +{ +public: + + explicit PositionsApi( std::shared_ptr apiClient ); + + virtual ~PositionsApi(); + + /// + /// Get open positions + /// + /// + /// Get current open positions across all or single exchange. + /// + /// Filter the balances to the specific exchange. (optional, default to utility::conversions::to_string_t("")) + pplx::task>> v1PositionsGet( + boost::optional exchangeId + ) const; + +protected: + std::shared_ptr m_ApiClient; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_API_PositionsApi_H_ */ + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/git_push.sh b/ems-cloud-mgmt-sdk/cpp-restsdk/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.cpp new file mode 100644 index 0000000000..5a7e871dc0 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.cpp @@ -0,0 +1,171 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Balance.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +Balance::Balance() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_DataIsSet = false; +} + +Balance::~Balance() +{ +} + +void Balance::validate() +{ + // TODO: implement validation +} + +web::json::value Balance::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_DataIsSet) + { + val[utility::conversions::to_string_t(U("data"))] = ModelBase::toJson(m_Data); + } + + return val; +} + +bool Balance::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("data")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("data"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_data; + ok &= ModelBase::fromJson(fieldValue, refVal_data); + setData(refVal_data); + } + } + return ok; +} + +void Balance::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_DataIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("data")), m_Data)); + } +} + +bool Balance::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("data")))) + { + std::vector> refVal_data; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("data"))), refVal_data ); + setData(refVal_data); + } + return ok; +} + +utility::string_t Balance::getExchangeId() const +{ + return m_Exchange_id; +} + +void Balance::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool Balance::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void Balance::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +std::vector>& Balance::getData() +{ + return m_Data; +} + +void Balance::setData(const std::vector>& value) +{ + m_Data = value; + m_DataIsSet = true; +} + +bool Balance::dataIsSet() const +{ + return m_DataIsSet; +} + +void Balance::unsetData() +{ + m_DataIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.h new file mode 100644 index 0000000000..c7b03fe09b --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance.h @@ -0,0 +1,91 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Balance.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_H_ + + +#include "ModelBase.h" + +#include +#include "model/Balance_data.h" +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class Balance + : public ModelBase +{ +public: + Balance(); + virtual ~Balance(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Balance members + + /// + /// Exchange identifier used to identify the routing destination. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// + /// + std::vector>& getData(); + bool dataIsSet() const; + void unsetData(); + + void setData(const std::vector>& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + std::vector> m_Data; + bool m_DataIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.cpp new file mode 100644 index 0000000000..5c3fd1fbe6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.cpp @@ -0,0 +1,448 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Balance_data.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +Balance_data::Balance_data() +{ + m_Asset_id_exchange = utility::conversions::to_string_t(""); + m_Asset_id_exchangeIsSet = false; + m_Asset_id_coinapi = utility::conversions::to_string_t(""); + m_Asset_id_coinapiIsSet = false; + m_Balance = 0.0; + m_BalanceIsSet = false; + m_Available = 0.0; + m_AvailableIsSet = false; + m_Locked = 0.0; + m_LockedIsSet = false; + m_Last_updated_by = utility::conversions::to_string_t(""); + m_Last_updated_byIsSet = false; + m_Rate_usd = 0.0; + m_Rate_usdIsSet = false; + m_Traded = 0.0; + m_TradedIsSet = false; +} + +Balance_data::~Balance_data() +{ +} + +void Balance_data::validate() +{ + // TODO: implement validation +} + +web::json::value Balance_data::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Asset_id_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("asset_id_exchange"))] = ModelBase::toJson(m_Asset_id_exchange); + } + if(m_Asset_id_coinapiIsSet) + { + val[utility::conversions::to_string_t(U("asset_id_coinapi"))] = ModelBase::toJson(m_Asset_id_coinapi); + } + if(m_BalanceIsSet) + { + val[utility::conversions::to_string_t(U("balance"))] = ModelBase::toJson(m_Balance); + } + if(m_AvailableIsSet) + { + val[utility::conversions::to_string_t(U("available"))] = ModelBase::toJson(m_Available); + } + if(m_LockedIsSet) + { + val[utility::conversions::to_string_t(U("locked"))] = ModelBase::toJson(m_Locked); + } + if(m_Last_updated_byIsSet) + { + val[utility::conversions::to_string_t(U("last_updated_by"))] = ModelBase::toJson(m_Last_updated_by); + } + if(m_Rate_usdIsSet) + { + val[utility::conversions::to_string_t(U("rate_usd"))] = ModelBase::toJson(m_Rate_usd); + } + if(m_TradedIsSet) + { + val[utility::conversions::to_string_t(U("traded"))] = ModelBase::toJson(m_Traded); + } + + return val; +} + +bool Balance_data::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("asset_id_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("asset_id_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_asset_id_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_asset_id_exchange); + setAssetIdExchange(refVal_asset_id_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("asset_id_coinapi")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("asset_id_coinapi"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_asset_id_coinapi; + ok &= ModelBase::fromJson(fieldValue, refVal_asset_id_coinapi); + setAssetIdCoinapi(refVal_asset_id_coinapi); + } + } + if(val.has_field(utility::conversions::to_string_t(U("balance")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("balance"))); + if(!fieldValue.is_null()) + { + double refVal_balance; + ok &= ModelBase::fromJson(fieldValue, refVal_balance); + setBalance(refVal_balance); + } + } + if(val.has_field(utility::conversions::to_string_t(U("available")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("available"))); + if(!fieldValue.is_null()) + { + double refVal_available; + ok &= ModelBase::fromJson(fieldValue, refVal_available); + setAvailable(refVal_available); + } + } + if(val.has_field(utility::conversions::to_string_t(U("locked")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("locked"))); + if(!fieldValue.is_null()) + { + double refVal_locked; + ok &= ModelBase::fromJson(fieldValue, refVal_locked); + setLocked(refVal_locked); + } + } + if(val.has_field(utility::conversions::to_string_t(U("last_updated_by")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("last_updated_by"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_last_updated_by; + ok &= ModelBase::fromJson(fieldValue, refVal_last_updated_by); + setLastUpdatedBy(refVal_last_updated_by); + } + } + if(val.has_field(utility::conversions::to_string_t(U("rate_usd")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("rate_usd"))); + if(!fieldValue.is_null()) + { + double refVal_rate_usd; + ok &= ModelBase::fromJson(fieldValue, refVal_rate_usd); + setRateUsd(refVal_rate_usd); + } + } + if(val.has_field(utility::conversions::to_string_t(U("traded")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("traded"))); + if(!fieldValue.is_null()) + { + double refVal_traded; + ok &= ModelBase::fromJson(fieldValue, refVal_traded); + setTraded(refVal_traded); + } + } + return ok; +} + +void Balance_data::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Asset_id_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("asset_id_exchange")), m_Asset_id_exchange)); + } + if(m_Asset_id_coinapiIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("asset_id_coinapi")), m_Asset_id_coinapi)); + } + if(m_BalanceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("balance")), m_Balance)); + } + if(m_AvailableIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("available")), m_Available)); + } + if(m_LockedIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("locked")), m_Locked)); + } + if(m_Last_updated_byIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("last_updated_by")), m_Last_updated_by)); + } + if(m_Rate_usdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("rate_usd")), m_Rate_usd)); + } + if(m_TradedIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("traded")), m_Traded)); + } +} + +bool Balance_data::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("asset_id_exchange")))) + { + utility::string_t refVal_asset_id_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("asset_id_exchange"))), refVal_asset_id_exchange ); + setAssetIdExchange(refVal_asset_id_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("asset_id_coinapi")))) + { + utility::string_t refVal_asset_id_coinapi; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("asset_id_coinapi"))), refVal_asset_id_coinapi ); + setAssetIdCoinapi(refVal_asset_id_coinapi); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("balance")))) + { + double refVal_balance; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("balance"))), refVal_balance ); + setBalance(refVal_balance); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("available")))) + { + double refVal_available; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("available"))), refVal_available ); + setAvailable(refVal_available); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("locked")))) + { + double refVal_locked; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("locked"))), refVal_locked ); + setLocked(refVal_locked); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("last_updated_by")))) + { + utility::string_t refVal_last_updated_by; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("last_updated_by"))), refVal_last_updated_by ); + setLastUpdatedBy(refVal_last_updated_by); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("rate_usd")))) + { + double refVal_rate_usd; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("rate_usd"))), refVal_rate_usd ); + setRateUsd(refVal_rate_usd); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("traded")))) + { + double refVal_traded; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("traded"))), refVal_traded ); + setTraded(refVal_traded); + } + return ok; +} + +utility::string_t Balance_data::getAssetIdExchange() const +{ + return m_Asset_id_exchange; +} + +void Balance_data::setAssetIdExchange(const utility::string_t& value) +{ + m_Asset_id_exchange = value; + m_Asset_id_exchangeIsSet = true; +} + +bool Balance_data::assetIdExchangeIsSet() const +{ + return m_Asset_id_exchangeIsSet; +} + +void Balance_data::unsetAsset_id_exchange() +{ + m_Asset_id_exchangeIsSet = false; +} +utility::string_t Balance_data::getAssetIdCoinapi() const +{ + return m_Asset_id_coinapi; +} + +void Balance_data::setAssetIdCoinapi(const utility::string_t& value) +{ + m_Asset_id_coinapi = value; + m_Asset_id_coinapiIsSet = true; +} + +bool Balance_data::assetIdCoinapiIsSet() const +{ + return m_Asset_id_coinapiIsSet; +} + +void Balance_data::unsetAsset_id_coinapi() +{ + m_Asset_id_coinapiIsSet = false; +} +double Balance_data::getBalance() const +{ + return m_Balance; +} + +void Balance_data::setBalance(double value) +{ + m_Balance = value; + m_BalanceIsSet = true; +} + +bool Balance_data::balanceIsSet() const +{ + return m_BalanceIsSet; +} + +void Balance_data::unsetBalance() +{ + m_BalanceIsSet = false; +} +double Balance_data::getAvailable() const +{ + return m_Available; +} + +void Balance_data::setAvailable(double value) +{ + m_Available = value; + m_AvailableIsSet = true; +} + +bool Balance_data::availableIsSet() const +{ + return m_AvailableIsSet; +} + +void Balance_data::unsetAvailable() +{ + m_AvailableIsSet = false; +} +double Balance_data::getLocked() const +{ + return m_Locked; +} + +void Balance_data::setLocked(double value) +{ + m_Locked = value; + m_LockedIsSet = true; +} + +bool Balance_data::lockedIsSet() const +{ + return m_LockedIsSet; +} + +void Balance_data::unsetLocked() +{ + m_LockedIsSet = false; +} +utility::string_t Balance_data::getLastUpdatedBy() const +{ + return m_Last_updated_by; +} + +void Balance_data::setLastUpdatedBy(const utility::string_t& value) +{ + m_Last_updated_by = value; + m_Last_updated_byIsSet = true; +} + +bool Balance_data::lastUpdatedByIsSet() const +{ + return m_Last_updated_byIsSet; +} + +void Balance_data::unsetLast_updated_by() +{ + m_Last_updated_byIsSet = false; +} +double Balance_data::getRateUsd() const +{ + return m_Rate_usd; +} + +void Balance_data::setRateUsd(double value) +{ + m_Rate_usd = value; + m_Rate_usdIsSet = true; +} + +bool Balance_data::rateUsdIsSet() const +{ + return m_Rate_usdIsSet; +} + +void Balance_data::unsetRate_usd() +{ + m_Rate_usdIsSet = false; +} +double Balance_data::getTraded() const +{ + return m_Traded; +} + +void Balance_data::setTraded(double value) +{ + m_Traded = value; + m_TradedIsSet = true; +} + +bool Balance_data::tradedIsSet() const +{ + return m_TradedIsSet; +} + +void Balance_data::unsetTraded() +{ + m_TradedIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.h new file mode 100644 index 0000000000..517f0e2d36 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Balance_data.h @@ -0,0 +1,155 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Balance_data.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_data_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_data_H_ + + +#include "ModelBase.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class Balance_data + : public ModelBase +{ +public: + Balance_data(); + virtual ~Balance_data(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Balance_data members + + /// + /// Exchange currency code. + /// + utility::string_t getAssetIdExchange() const; + bool assetIdExchangeIsSet() const; + void unsetAsset_id_exchange(); + + void setAssetIdExchange(const utility::string_t& value); + + /// + /// CoinAPI currency code. + /// + utility::string_t getAssetIdCoinapi() const; + bool assetIdCoinapiIsSet() const; + void unsetAsset_id_coinapi(); + + void setAssetIdCoinapi(const utility::string_t& value); + + /// + /// Value of the current total currency balance on the exchange. + /// + double getBalance() const; + bool balanceIsSet() const; + void unsetBalance(); + + void setBalance(double value); + + /// + /// Value of the current available currency balance on the exchange that can be used as collateral. + /// + double getAvailable() const; + bool availableIsSet() const; + void unsetAvailable(); + + void setAvailable(double value); + + /// + /// Value of the current locked currency balance by the exchange. + /// + double getLocked() const; + bool lockedIsSet() const; + void unsetLocked(); + + void setLocked(double value); + + /// + /// Source of the last modification. + /// + utility::string_t getLastUpdatedBy() const; + bool lastUpdatedByIsSet() const; + void unsetLast_updated_by(); + + void setLastUpdatedBy(const utility::string_t& value); + + /// + /// Current exchange rate to the USD for the single unit of the currency. + /// + double getRateUsd() const; + bool rateUsdIsSet() const; + void unsetRate_usd(); + + void setRateUsd(double value); + + /// + /// Value of the current total traded. + /// + double getTraded() const; + bool tradedIsSet() const; + void unsetTraded(); + + void setTraded(double value); + + +protected: + utility::string_t m_Asset_id_exchange; + bool m_Asset_id_exchangeIsSet; + utility::string_t m_Asset_id_coinapi; + bool m_Asset_id_coinapiIsSet; + double m_Balance; + bool m_BalanceIsSet; + double m_Available; + bool m_AvailableIsSet; + double m_Locked; + bool m_LockedIsSet; + utility::string_t m_Last_updated_by; + bool m_Last_updated_byIsSet; + double m_Rate_usd; + bool m_Rate_usdIsSet; + double m_Traded; + bool m_TradedIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Balance_data_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.cpp new file mode 100644 index 0000000000..9e64c96382 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.cpp @@ -0,0 +1,217 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Fills.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +Fills::Fills() +{ + m_TimeIsSet = false; + m_Price = 0.0; + m_PriceIsSet = false; + m_Amount = 0.0; + m_AmountIsSet = false; +} + +Fills::~Fills() +{ +} + +void Fills::validate() +{ + // TODO: implement validation +} + +web::json::value Fills::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_TimeIsSet) + { + val[utility::conversions::to_string_t(U("time"))] = ModelBase::toJson(m_Time); + } + if(m_PriceIsSet) + { + val[utility::conversions::to_string_t(U("price"))] = ModelBase::toJson(m_Price); + } + if(m_AmountIsSet) + { + val[utility::conversions::to_string_t(U("amount"))] = ModelBase::toJson(m_Amount); + } + + return val; +} + +bool Fills::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("time")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("time"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_time; + ok &= ModelBase::fromJson(fieldValue, refVal_time); + setTime(refVal_time); + } + } + if(val.has_field(utility::conversions::to_string_t(U("price")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("price"))); + if(!fieldValue.is_null()) + { + double refVal_price; + ok &= ModelBase::fromJson(fieldValue, refVal_price); + setPrice(refVal_price); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount"))); + if(!fieldValue.is_null()) + { + double refVal_amount; + ok &= ModelBase::fromJson(fieldValue, refVal_amount); + setAmount(refVal_amount); + } + } + return ok; +} + +void Fills::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_TimeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("time")), m_Time)); + } + if(m_PriceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("price")), m_Price)); + } + if(m_AmountIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount")), m_Amount)); + } +} + +bool Fills::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("time")))) + { + std::shared_ptr refVal_time; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("time"))), refVal_time ); + setTime(refVal_time); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("price")))) + { + double refVal_price; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("price"))), refVal_price ); + setPrice(refVal_price); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount")))) + { + double refVal_amount; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount"))), refVal_amount ); + setAmount(refVal_amount); + } + return ok; +} + +std::shared_ptr Fills::getTime() const +{ + return m_Time; +} + +void Fills::setTime(const std::shared_ptr& value) +{ + m_Time = value; + m_TimeIsSet = true; +} + +bool Fills::timeIsSet() const +{ + return m_TimeIsSet; +} + +void Fills::unsetTime() +{ + m_TimeIsSet = false; +} +double Fills::getPrice() const +{ + return m_Price; +} + +void Fills::setPrice(double value) +{ + m_Price = value; + m_PriceIsSet = true; +} + +bool Fills::priceIsSet() const +{ + return m_PriceIsSet; +} + +void Fills::unsetPrice() +{ + m_PriceIsSet = false; +} +double Fills::getAmount() const +{ + return m_Amount; +} + +void Fills::setAmount(double value) +{ + m_Amount = value; + m_AmountIsSet = true; +} + +bool Fills::amountIsSet() const +{ + return m_AmountIsSet; +} + +void Fills::unsetAmount() +{ + m_AmountIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.h new file mode 100644 index 0000000000..2bfc08a291 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Fills.h @@ -0,0 +1,100 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Fills.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Fills_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Fills_H_ + + +#include "ModelBase.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class Fills + : public ModelBase +{ +public: + Fills(); + virtual ~Fills(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Fills members + + /// + /// Execution time. + /// + std::shared_ptr getTime() const; + bool timeIsSet() const; + void unsetTime(); + + void setTime(const std::shared_ptr& value); + + /// + /// Execution price. + /// + double getPrice() const; + bool priceIsSet() const; + void unsetPrice(); + + void setPrice(double value); + + /// + /// Executed quantity. + /// + double getAmount() const; + bool amountIsSet() const; + void unsetAmount(); + + void setAmount(double value); + + +protected: + std::shared_ptr m_Time; + bool m_TimeIsSet; + double m_Price; + bool m_PriceIsSet; + double m_Amount; + bool m_AmountIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Fills_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.cpp new file mode 100644 index 0000000000..2f43d8f795 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.cpp @@ -0,0 +1,309 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "MessageReject.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +MessageReject::MessageReject() +{ + m_Type = utility::conversions::to_string_t(""); + m_TypeIsSet = false; + m_Reject_reasonIsSet = false; + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_Message = utility::conversions::to_string_t(""); + m_MessageIsSet = false; + m_Rejected_message = utility::conversions::to_string_t(""); + m_Rejected_messageIsSet = false; +} + +MessageReject::~MessageReject() +{ +} + +void MessageReject::validate() +{ + // TODO: implement validation +} + +web::json::value MessageReject::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_TypeIsSet) + { + val[utility::conversions::to_string_t(U("type"))] = ModelBase::toJson(m_Type); + } + if(m_Reject_reasonIsSet) + { + val[utility::conversions::to_string_t(U("reject_reason"))] = ModelBase::toJson(m_Reject_reason); + } + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_MessageIsSet) + { + val[utility::conversions::to_string_t(U("message"))] = ModelBase::toJson(m_Message); + } + if(m_Rejected_messageIsSet) + { + val[utility::conversions::to_string_t(U("rejected_message"))] = ModelBase::toJson(m_Rejected_message); + } + + return val; +} + +bool MessageReject::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("type")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("type"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_type; + ok &= ModelBase::fromJson(fieldValue, refVal_type); + setType(refVal_type); + } + } + if(val.has_field(utility::conversions::to_string_t(U("reject_reason")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("reject_reason"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_reject_reason; + ok &= ModelBase::fromJson(fieldValue, refVal_reject_reason); + setRejectReason(refVal_reject_reason); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("message")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("message"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_message; + ok &= ModelBase::fromJson(fieldValue, refVal_message); + setMessage(refVal_message); + } + } + if(val.has_field(utility::conversions::to_string_t(U("rejected_message")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("rejected_message"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_rejected_message; + ok &= ModelBase::fromJson(fieldValue, refVal_rejected_message); + setRejectedMessage(refVal_rejected_message); + } + } + return ok; +} + +void MessageReject::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_TypeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("type")), m_Type)); + } + if(m_Reject_reasonIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("reject_reason")), m_Reject_reason)); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_MessageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("message")), m_Message)); + } + if(m_Rejected_messageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("rejected_message")), m_Rejected_message)); + } +} + +bool MessageReject::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("type")))) + { + utility::string_t refVal_type; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("type"))), refVal_type ); + setType(refVal_type); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("reject_reason")))) + { + std::shared_ptr refVal_reject_reason; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("reject_reason"))), refVal_reject_reason ); + setRejectReason(refVal_reject_reason); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("message")))) + { + utility::string_t refVal_message; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("message"))), refVal_message ); + setMessage(refVal_message); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("rejected_message")))) + { + utility::string_t refVal_rejected_message; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("rejected_message"))), refVal_rejected_message ); + setRejectedMessage(refVal_rejected_message); + } + return ok; +} + +utility::string_t MessageReject::getType() const +{ + return m_Type; +} + +void MessageReject::setType(const utility::string_t& value) +{ + m_Type = value; + m_TypeIsSet = true; +} + +bool MessageReject::typeIsSet() const +{ + return m_TypeIsSet; +} + +void MessageReject::unsetType() +{ + m_TypeIsSet = false; +} +std::shared_ptr MessageReject::getRejectReason() const +{ + return m_Reject_reason; +} + +void MessageReject::setRejectReason(const std::shared_ptr& value) +{ + m_Reject_reason = value; + m_Reject_reasonIsSet = true; +} + +bool MessageReject::rejectReasonIsSet() const +{ + return m_Reject_reasonIsSet; +} + +void MessageReject::unsetReject_reason() +{ + m_Reject_reasonIsSet = false; +} +utility::string_t MessageReject::getExchangeId() const +{ + return m_Exchange_id; +} + +void MessageReject::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool MessageReject::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void MessageReject::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +utility::string_t MessageReject::getMessage() const +{ + return m_Message; +} + +void MessageReject::setMessage(const utility::string_t& value) +{ + m_Message = value; + m_MessageIsSet = true; +} + +bool MessageReject::messageIsSet() const +{ + return m_MessageIsSet; +} + +void MessageReject::unsetMessage() +{ + m_MessageIsSet = false; +} +utility::string_t MessageReject::getRejectedMessage() const +{ + return m_Rejected_message; +} + +void MessageReject::setRejectedMessage(const utility::string_t& value) +{ + m_Rejected_message = value; + m_Rejected_messageIsSet = true; +} + +bool MessageReject::rejectedMessageIsSet() const +{ + return m_Rejected_messageIsSet; +} + +void MessageReject::unsetRejected_message() +{ + m_Rejected_messageIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.h new file mode 100644 index 0000000000..cfb38efe60 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/MessageReject.h @@ -0,0 +1,123 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * MessageReject.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_MessageReject_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_MessageReject_H_ + + +#include "ModelBase.h" + +#include +#include "model/RejectReason.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class MessageReject + : public ModelBase +{ +public: + MessageReject(); + virtual ~MessageReject(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// MessageReject members + + /// + /// Message type, constant. + /// + utility::string_t getType() const; + bool typeIsSet() const; + void unsetType(); + + void setType(const utility::string_t& value); + + /// + /// + /// + std::shared_ptr getRejectReason() const; + bool rejectReasonIsSet() const; + void unsetReject_reason(); + + void setRejectReason(const std::shared_ptr& value); + + /// + /// If the message related to exchange, then the identifier of the exchange will be provided. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// Message text. + /// + utility::string_t getMessage() const; + bool messageIsSet() const; + void unsetMessage(); + + void setMessage(const utility::string_t& value); + + /// + /// Value of rejected request, if available. + /// + utility::string_t getRejectedMessage() const; + bool rejectedMessageIsSet() const; + void unsetRejected_message(); + + void setRejectedMessage(const utility::string_t& value); + + +protected: + utility::string_t m_Type; + bool m_TypeIsSet; + std::shared_ptr m_Reject_reason; + bool m_Reject_reasonIsSet; + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + utility::string_t m_Message; + bool m_MessageIsSet; + utility::string_t m_Rejected_message; + bool m_Rejected_messageIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_MessageReject_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.cpp new file mode 100644 index 0000000000..7558227fa4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.cpp @@ -0,0 +1,125 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrdSide.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +namespace +{ +using EnumUnderlyingType = utility::string_t; + +OrdSide::eOrdSide toEnum(const EnumUnderlyingType& val) +{ + if (val == utility::conversions::to_string_t(U("BUY"))) + return OrdSide::eOrdSide::OrdSide_BUY; + if (val == utility::conversions::to_string_t(U("SELL"))) + return OrdSide::eOrdSide::OrdSide_SELL; + return {}; +} + +EnumUnderlyingType fromEnum(OrdSide::eOrdSide e) +{ + switch (e) + { + case OrdSide::eOrdSide::OrdSide_BUY: + return U("BUY"); + case OrdSide::eOrdSide::OrdSide_SELL: + return U("SELL"); + default: + break; + } + return {}; +} +} + +OrdSide::OrdSide() +{ +} + +OrdSide::~OrdSide() +{ +} + +void OrdSide::validate() +{ + // TODO: implement validation +} + +web::json::value OrdSide::toJson() const +{ + auto val = fromEnum(m_value); + return web::json::value(val); +} + +bool OrdSide::fromJson(const web::json::value& val) +{ + m_value = toEnum(val.as_string()); + return true; +} + +void OrdSide::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + + auto e = fromEnum(m_value); + multipart->add(ModelBase::toHttpContent(namePrefix, e)); +} + +bool OrdSide::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + { + EnumUnderlyingType e; + ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e); + if (ok) + { + auto v = toEnum(e); + setValue(v); + } + } + return ok; +} + +OrdSide::eOrdSide OrdSide::getValue() const +{ + return m_value; +} + +void OrdSide::setValue(OrdSide::eOrdSide const value) +{ + m_value = value; +} + + +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.h new file mode 100644 index 0000000000..b10bed19e5 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdSide.h @@ -0,0 +1,67 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrdSide.h + * + * Side of order. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrdSide_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrdSide_H_ + + +#include "ModelBase.h" + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class OrdSide + : public ModelBase +{ +public: + OrdSide(); + virtual ~OrdSide(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + enum class eOrdSide + { + OrdSide_BUY, + OrdSide_SELL, + }; + + eOrdSide getValue() const; + void setValue(eOrdSide const value); + + protected: + eOrdSide m_value; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrdSide_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.cpp new file mode 100644 index 0000000000..081214235c --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.cpp @@ -0,0 +1,153 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrdStatus.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +namespace +{ +using EnumUnderlyingType = utility::string_t; + +OrdStatus::eOrdStatus toEnum(const EnumUnderlyingType& val) +{ + if (val == utility::conversions::to_string_t(U("RECEIVED"))) + return OrdStatus::eOrdStatus::OrdStatus_RECEIVED; + if (val == utility::conversions::to_string_t(U("ROUTING"))) + return OrdStatus::eOrdStatus::OrdStatus_ROUTING; + if (val == utility::conversions::to_string_t(U("ROUTED"))) + return OrdStatus::eOrdStatus::OrdStatus_ROUTED; + if (val == utility::conversions::to_string_t(U("NEW"))) + return OrdStatus::eOrdStatus::OrdStatus_NEW; + if (val == utility::conversions::to_string_t(U("PENDING_CANCEL"))) + return OrdStatus::eOrdStatus::OrdStatus_PENDING_CANCEL; + if (val == utility::conversions::to_string_t(U("PARTIALLY_FILLED"))) + return OrdStatus::eOrdStatus::OrdStatus_PARTIALLY_FILLED; + if (val == utility::conversions::to_string_t(U("FILLED"))) + return OrdStatus::eOrdStatus::OrdStatus_FILLED; + if (val == utility::conversions::to_string_t(U("CANCELED"))) + return OrdStatus::eOrdStatus::OrdStatus_CANCELED; + if (val == utility::conversions::to_string_t(U("REJECTED"))) + return OrdStatus::eOrdStatus::OrdStatus_REJECTED; + return {}; +} + +EnumUnderlyingType fromEnum(OrdStatus::eOrdStatus e) +{ + switch (e) + { + case OrdStatus::eOrdStatus::OrdStatus_RECEIVED: + return U("RECEIVED"); + case OrdStatus::eOrdStatus::OrdStatus_ROUTING: + return U("ROUTING"); + case OrdStatus::eOrdStatus::OrdStatus_ROUTED: + return U("ROUTED"); + case OrdStatus::eOrdStatus::OrdStatus_NEW: + return U("NEW"); + case OrdStatus::eOrdStatus::OrdStatus_PENDING_CANCEL: + return U("PENDING_CANCEL"); + case OrdStatus::eOrdStatus::OrdStatus_PARTIALLY_FILLED: + return U("PARTIALLY_FILLED"); + case OrdStatus::eOrdStatus::OrdStatus_FILLED: + return U("FILLED"); + case OrdStatus::eOrdStatus::OrdStatus_CANCELED: + return U("CANCELED"); + case OrdStatus::eOrdStatus::OrdStatus_REJECTED: + return U("REJECTED"); + default: + break; + } + return {}; +} +} + +OrdStatus::OrdStatus() +{ +} + +OrdStatus::~OrdStatus() +{ +} + +void OrdStatus::validate() +{ + // TODO: implement validation +} + +web::json::value OrdStatus::toJson() const +{ + auto val = fromEnum(m_value); + return web::json::value(val); +} + +bool OrdStatus::fromJson(const web::json::value& val) +{ + m_value = toEnum(val.as_string()); + return true; +} + +void OrdStatus::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + + auto e = fromEnum(m_value); + multipart->add(ModelBase::toHttpContent(namePrefix, e)); +} + +bool OrdStatus::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + { + EnumUnderlyingType e; + ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e); + if (ok) + { + auto v = toEnum(e); + setValue(v); + } + } + return ok; +} + +OrdStatus::eOrdStatus OrdStatus::getValue() const +{ + return m_value; +} + +void OrdStatus::setValue(OrdStatus::eOrdStatus const value) +{ + m_value = value; +} + + +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.h new file mode 100644 index 0000000000..192dfb118e --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdStatus.h @@ -0,0 +1,74 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrdStatus.h + * + * Order statuses and the lifecycle are documented in the separate section: <a href=\"#ems-order-lifecycle\">EMS / Starter Guide / Order Lifecycle</a> + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrdStatus_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrdStatus_H_ + + +#include "ModelBase.h" + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class OrdStatus + : public ModelBase +{ +public: + OrdStatus(); + virtual ~OrdStatus(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + enum class eOrdStatus + { + OrdStatus_RECEIVED, + OrdStatus_ROUTING, + OrdStatus_ROUTED, + OrdStatus_NEW, + OrdStatus_PENDING_CANCEL, + OrdStatus_PARTIALLY_FILLED, + OrdStatus_FILLED, + OrdStatus_CANCELED, + OrdStatus_REJECTED, + }; + + eOrdStatus getValue() const; + void setValue(eOrdStatus const value); + + protected: + eOrdStatus m_value; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrdStatus_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.cpp new file mode 100644 index 0000000000..6f058b3d6d --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.cpp @@ -0,0 +1,121 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrdType.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +namespace +{ +using EnumUnderlyingType = utility::string_t; + +OrdType::eOrdType toEnum(const EnumUnderlyingType& val) +{ + if (val == utility::conversions::to_string_t(U("LIMIT"))) + return OrdType::eOrdType::OrdType_LIMIT; + return {}; +} + +EnumUnderlyingType fromEnum(OrdType::eOrdType e) +{ + switch (e) + { + case OrdType::eOrdType::OrdType_LIMIT: + return U("LIMIT"); + default: + break; + } + return {}; +} +} + +OrdType::OrdType() +{ +} + +OrdType::~OrdType() +{ +} + +void OrdType::validate() +{ + // TODO: implement validation +} + +web::json::value OrdType::toJson() const +{ + auto val = fromEnum(m_value); + return web::json::value(val); +} + +bool OrdType::fromJson(const web::json::value& val) +{ + m_value = toEnum(val.as_string()); + return true; +} + +void OrdType::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + + auto e = fromEnum(m_value); + multipart->add(ModelBase::toHttpContent(namePrefix, e)); +} + +bool OrdType::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + { + EnumUnderlyingType e; + ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e); + if (ok) + { + auto v = toEnum(e); + setValue(v); + } + } + return ok; +} + +OrdType::eOrdType OrdType::getValue() const +{ + return m_value; +} + +void OrdType::setValue(OrdType::eOrdType const value) +{ + m_value = value; +} + + +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.h new file mode 100644 index 0000000000..79f8766847 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrdType.h @@ -0,0 +1,66 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrdType.h + * + * Order types are documented in the separate section: <a href=\"#ems-order-params-type\">EMS / Starter Guide / Order parameters / Order type</a> + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrdType_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrdType_H_ + + +#include "ModelBase.h" + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class OrdType + : public ModelBase +{ +public: + OrdType(); + virtual ~OrdType(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + enum class eOrdType + { + OrdType_LIMIT, + }; + + eOrdType getValue() const; + void setValue(eOrdType const value); + + protected: + eOrdType m_value; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrdType_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.cpp new file mode 100644 index 0000000000..7763576c0e --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.cpp @@ -0,0 +1,126 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrderCancelAllRequest.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +OrderCancelAllRequest::OrderCancelAllRequest() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; +} + +OrderCancelAllRequest::~OrderCancelAllRequest() +{ +} + +void OrderCancelAllRequest::validate() +{ + // TODO: implement validation +} + +web::json::value OrderCancelAllRequest::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + + return val; +} + +bool OrderCancelAllRequest::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + return ok; +} + +void OrderCancelAllRequest::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } +} + +bool OrderCancelAllRequest::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + return ok; +} + +utility::string_t OrderCancelAllRequest::getExchangeId() const +{ + return m_Exchange_id; +} + +void OrderCancelAllRequest::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool OrderCancelAllRequest::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void OrderCancelAllRequest::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.h new file mode 100644 index 0000000000..aed2b99e24 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelAllRequest.h @@ -0,0 +1,78 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrderCancelAllRequest.h + * + * Cancel all orders request object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelAllRequest_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelAllRequest_H_ + + +#include "ModelBase.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// Cancel all orders request object. +/// +class OrderCancelAllRequest + : public ModelBase +{ +public: + OrderCancelAllRequest(); + virtual ~OrderCancelAllRequest(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// OrderCancelAllRequest members + + /// + /// Identifier of the exchange from which active orders should be canceled. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelAllRequest_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.cpp new file mode 100644 index 0000000000..46f5c2bd5e --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.cpp @@ -0,0 +1,218 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrderCancelSingleRequest.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +OrderCancelSingleRequest::OrderCancelSingleRequest() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_Exchange_order_id = utility::conversions::to_string_t(""); + m_Exchange_order_idIsSet = false; + m_Client_order_id = utility::conversions::to_string_t(""); + m_Client_order_idIsSet = false; +} + +OrderCancelSingleRequest::~OrderCancelSingleRequest() +{ +} + +void OrderCancelSingleRequest::validate() +{ + // TODO: implement validation +} + +web::json::value OrderCancelSingleRequest::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_Exchange_order_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_order_id"))] = ModelBase::toJson(m_Exchange_order_id); + } + if(m_Client_order_idIsSet) + { + val[utility::conversions::to_string_t(U("client_order_id"))] = ModelBase::toJson(m_Client_order_id); + } + + return val; +} + +bool OrderCancelSingleRequest::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exchange_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_order_id); + setExchangeOrderId(refVal_exchange_order_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("client_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("client_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_client_order_id); + setClientOrderId(refVal_client_order_id); + } + } + return ok; +} + +void OrderCancelSingleRequest::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_Exchange_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_order_id")), m_Exchange_order_id)); + } + if(m_Client_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("client_order_id")), m_Client_order_id)); + } +} + +bool OrderCancelSingleRequest::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_order_id")))) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_order_id"))), refVal_exchange_order_id ); + setExchangeOrderId(refVal_exchange_order_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("client_order_id")))) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("client_order_id"))), refVal_client_order_id ); + setClientOrderId(refVal_client_order_id); + } + return ok; +} + +utility::string_t OrderCancelSingleRequest::getExchangeId() const +{ + return m_Exchange_id; +} + +void OrderCancelSingleRequest::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool OrderCancelSingleRequest::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void OrderCancelSingleRequest::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +utility::string_t OrderCancelSingleRequest::getExchangeOrderId() const +{ + return m_Exchange_order_id; +} + +void OrderCancelSingleRequest::setExchangeOrderId(const utility::string_t& value) +{ + m_Exchange_order_id = value; + m_Exchange_order_idIsSet = true; +} + +bool OrderCancelSingleRequest::exchangeOrderIdIsSet() const +{ + return m_Exchange_order_idIsSet; +} + +void OrderCancelSingleRequest::unsetExchange_order_id() +{ + m_Exchange_order_idIsSet = false; +} +utility::string_t OrderCancelSingleRequest::getClientOrderId() const +{ + return m_Client_order_id; +} + +void OrderCancelSingleRequest::setClientOrderId(const utility::string_t& value) +{ + m_Client_order_id = value; + m_Client_order_idIsSet = true; +} + +bool OrderCancelSingleRequest::clientOrderIdIsSet() const +{ + return m_Client_order_idIsSet; +} + +void OrderCancelSingleRequest::unsetClient_order_id() +{ + m_Client_order_idIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.h new file mode 100644 index 0000000000..4c42c71166 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderCancelSingleRequest.h @@ -0,0 +1,100 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrderCancelSingleRequest.h + * + * Cancel single order request object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelSingleRequest_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelSingleRequest_H_ + + +#include "ModelBase.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// Cancel single order request object. +/// +class OrderCancelSingleRequest + : public ModelBase +{ +public: + OrderCancelSingleRequest(); + virtual ~OrderCancelSingleRequest(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// OrderCancelSingleRequest members + + /// + /// Exchange identifier used to identify the routing destination. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// Unique identifier of the order assigned by the exchange or executing system. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + /// + utility::string_t getExchangeOrderId() const; + bool exchangeOrderIdIsSet() const; + void unsetExchange_order_id(); + + void setExchangeOrderId(const utility::string_t& value); + + /// + /// The unique identifier of the order assigned by the client. One of the properties (`exchange_order_id`, `client_order_id`) is required to identify the new order. + /// + utility::string_t getClientOrderId() const; + bool clientOrderIdIsSet() const; + void unsetClient_order_id(); + + void setClientOrderId(const utility::string_t& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + utility::string_t m_Exchange_order_id; + bool m_Exchange_order_idIsSet; + utility::string_t m_Client_order_id; + bool m_Client_order_idIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrderCancelSingleRequest_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.cpp new file mode 100644 index 0000000000..5d2bdf49da --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.cpp @@ -0,0 +1,992 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrderExecutionReport.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +OrderExecutionReport::OrderExecutionReport() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_Client_order_id = utility::conversions::to_string_t(""); + m_Client_order_idIsSet = false; + m_Symbol_id_exchange = utility::conversions::to_string_t(""); + m_Symbol_id_exchangeIsSet = false; + m_Symbol_id_coinapi = utility::conversions::to_string_t(""); + m_Symbol_id_coinapiIsSet = false; + m_Amount_order = 0.0; + m_Amount_orderIsSet = false; + m_Price = 0.0; + m_PriceIsSet = false; + m_SideIsSet = false; + m_Order_typeIsSet = false; + m_Time_in_forceIsSet = false; + m_Expire_timeIsSet = false; + m_Exec_instIsSet = false; + m_Client_order_id_format_exchange = utility::conversions::to_string_t(""); + m_Client_order_id_format_exchangeIsSet = false; + m_Exchange_order_id = utility::conversions::to_string_t(""); + m_Exchange_order_idIsSet = false; + m_Amount_open = 0.0; + m_Amount_openIsSet = false; + m_Amount_filled = 0.0; + m_Amount_filledIsSet = false; + m_Avg_px = 0.0; + m_Avg_pxIsSet = false; + m_StatusIsSet = false; + m_Status_historyIsSet = false; + m_Error_message = utility::conversions::to_string_t(""); + m_Error_messageIsSet = false; + m_FillsIsSet = false; +} + +OrderExecutionReport::~OrderExecutionReport() +{ +} + +void OrderExecutionReport::validate() +{ + // TODO: implement validation +} + +web::json::value OrderExecutionReport::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_Client_order_idIsSet) + { + val[utility::conversions::to_string_t(U("client_order_id"))] = ModelBase::toJson(m_Client_order_id); + } + if(m_Symbol_id_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_exchange"))] = ModelBase::toJson(m_Symbol_id_exchange); + } + if(m_Symbol_id_coinapiIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_coinapi"))] = ModelBase::toJson(m_Symbol_id_coinapi); + } + if(m_Amount_orderIsSet) + { + val[utility::conversions::to_string_t(U("amount_order"))] = ModelBase::toJson(m_Amount_order); + } + if(m_PriceIsSet) + { + val[utility::conversions::to_string_t(U("price"))] = ModelBase::toJson(m_Price); + } + if(m_SideIsSet) + { + val[utility::conversions::to_string_t(U("side"))] = ModelBase::toJson(m_Side); + } + if(m_Order_typeIsSet) + { + val[utility::conversions::to_string_t(U("order_type"))] = ModelBase::toJson(m_Order_type); + } + if(m_Time_in_forceIsSet) + { + val[utility::conversions::to_string_t(U("time_in_force"))] = ModelBase::toJson(m_Time_in_force); + } + if(m_Expire_timeIsSet) + { + val[utility::conversions::to_string_t(U("expire_time"))] = ModelBase::toJson(m_Expire_time); + } + if(m_Exec_instIsSet) + { + val[utility::conversions::to_string_t(U("exec_inst"))] = ModelBase::toJson(m_Exec_inst); + } + if(m_Client_order_id_format_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("client_order_id_format_exchange"))] = ModelBase::toJson(m_Client_order_id_format_exchange); + } + if(m_Exchange_order_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_order_id"))] = ModelBase::toJson(m_Exchange_order_id); + } + if(m_Amount_openIsSet) + { + val[utility::conversions::to_string_t(U("amount_open"))] = ModelBase::toJson(m_Amount_open); + } + if(m_Amount_filledIsSet) + { + val[utility::conversions::to_string_t(U("amount_filled"))] = ModelBase::toJson(m_Amount_filled); + } + if(m_Avg_pxIsSet) + { + val[utility::conversions::to_string_t(U("avg_px"))] = ModelBase::toJson(m_Avg_px); + } + if(m_StatusIsSet) + { + val[utility::conversions::to_string_t(U("status"))] = ModelBase::toJson(m_Status); + } + if(m_Status_historyIsSet) + { + val[utility::conversions::to_string_t(U("status_history"))] = ModelBase::toJson(m_Status_history); + } + if(m_Error_messageIsSet) + { + val[utility::conversions::to_string_t(U("error_message"))] = ModelBase::toJson(m_Error_message); + } + if(m_FillsIsSet) + { + val[utility::conversions::to_string_t(U("fills"))] = ModelBase::toJson(m_Fills); + } + + return val; +} + +bool OrderExecutionReport::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("client_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("client_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_client_order_id); + setClientOrderId(refVal_client_order_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_exchange); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_coinapi"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_coinapi); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_order")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_order"))); + if(!fieldValue.is_null()) + { + double refVal_amount_order; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_order); + setAmountOrder(refVal_amount_order); + } + } + if(val.has_field(utility::conversions::to_string_t(U("price")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("price"))); + if(!fieldValue.is_null()) + { + double refVal_price; + ok &= ModelBase::fromJson(fieldValue, refVal_price); + setPrice(refVal_price); + } + } + if(val.has_field(utility::conversions::to_string_t(U("side")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("side"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromJson(fieldValue, refVal_side); + setSide(refVal_side); + } + } + if(val.has_field(utility::conversions::to_string_t(U("order_type")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("order_type"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_order_type; + ok &= ModelBase::fromJson(fieldValue, refVal_order_type); + setOrderType(refVal_order_type); + } + } + if(val.has_field(utility::conversions::to_string_t(U("time_in_force")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("time_in_force"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_time_in_force; + ok &= ModelBase::fromJson(fieldValue, refVal_time_in_force); + setTimeInForce(refVal_time_in_force); + } + } + if(val.has_field(utility::conversions::to_string_t(U("expire_time")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("expire_time"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_expire_time; + ok &= ModelBase::fromJson(fieldValue, refVal_expire_time); + setExpireTime(refVal_expire_time); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exec_inst")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exec_inst"))); + if(!fieldValue.is_null()) + { + std::vector refVal_exec_inst; + ok &= ModelBase::fromJson(fieldValue, refVal_exec_inst); + setExecInst(refVal_exec_inst); + } + } + if(val.has_field(utility::conversions::to_string_t(U("client_order_id_format_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("client_order_id_format_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_client_order_id_format_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_client_order_id_format_exchange); + setClientOrderIdFormatExchange(refVal_client_order_id_format_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exchange_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_order_id); + setExchangeOrderId(refVal_exchange_order_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_open")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_open"))); + if(!fieldValue.is_null()) + { + double refVal_amount_open; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_open); + setAmountOpen(refVal_amount_open); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_filled")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_filled"))); + if(!fieldValue.is_null()) + { + double refVal_amount_filled; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_filled); + setAmountFilled(refVal_amount_filled); + } + } + if(val.has_field(utility::conversions::to_string_t(U("avg_px")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("avg_px"))); + if(!fieldValue.is_null()) + { + double refVal_avg_px; + ok &= ModelBase::fromJson(fieldValue, refVal_avg_px); + setAvgPx(refVal_avg_px); + } + } + if(val.has_field(utility::conversions::to_string_t(U("status")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("status"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_status; + ok &= ModelBase::fromJson(fieldValue, refVal_status); + setStatus(refVal_status); + } + } + if(val.has_field(utility::conversions::to_string_t(U("status_history")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("status_history"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_status_history; + ok &= ModelBase::fromJson(fieldValue, refVal_status_history); + setStatusHistory(refVal_status_history); + } + } + if(val.has_field(utility::conversions::to_string_t(U("error_message")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("error_message"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_error_message; + ok &= ModelBase::fromJson(fieldValue, refVal_error_message); + setErrorMessage(refVal_error_message); + } + } + if(val.has_field(utility::conversions::to_string_t(U("fills")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("fills"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_fills; + ok &= ModelBase::fromJson(fieldValue, refVal_fills); + setFills(refVal_fills); + } + } + return ok; +} + +void OrderExecutionReport::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_Client_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("client_order_id")), m_Client_order_id)); + } + if(m_Symbol_id_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_exchange")), m_Symbol_id_exchange)); + } + if(m_Symbol_id_coinapiIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_coinapi")), m_Symbol_id_coinapi)); + } + if(m_Amount_orderIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_order")), m_Amount_order)); + } + if(m_PriceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("price")), m_Price)); + } + if(m_SideIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("side")), m_Side)); + } + if(m_Order_typeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("order_type")), m_Order_type)); + } + if(m_Time_in_forceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("time_in_force")), m_Time_in_force)); + } + if(m_Expire_timeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("expire_time")), m_Expire_time)); + } + if(m_Exec_instIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exec_inst")), m_Exec_inst)); + } + if(m_Client_order_id_format_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("client_order_id_format_exchange")), m_Client_order_id_format_exchange)); + } + if(m_Exchange_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_order_id")), m_Exchange_order_id)); + } + if(m_Amount_openIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_open")), m_Amount_open)); + } + if(m_Amount_filledIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_filled")), m_Amount_filled)); + } + if(m_Avg_pxIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("avg_px")), m_Avg_px)); + } + if(m_StatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("status")), m_Status)); + } + if(m_Status_historyIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("status_history")), m_Status_history)); + } + if(m_Error_messageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("error_message")), m_Error_message)); + } + if(m_FillsIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("fills")), m_Fills)); + } +} + +bool OrderExecutionReport::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("client_order_id")))) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("client_order_id"))), refVal_client_order_id ); + setClientOrderId(refVal_client_order_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_exchange"))), refVal_symbol_id_exchange ); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_coinapi"))), refVal_symbol_id_coinapi ); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_order")))) + { + double refVal_amount_order; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_order"))), refVal_amount_order ); + setAmountOrder(refVal_amount_order); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("price")))) + { + double refVal_price; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("price"))), refVal_price ); + setPrice(refVal_price); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("side")))) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("side"))), refVal_side ); + setSide(refVal_side); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("order_type")))) + { + std::shared_ptr refVal_order_type; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("order_type"))), refVal_order_type ); + setOrderType(refVal_order_type); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("time_in_force")))) + { + std::shared_ptr refVal_time_in_force; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("time_in_force"))), refVal_time_in_force ); + setTimeInForce(refVal_time_in_force); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("expire_time")))) + { + std::shared_ptr refVal_expire_time; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("expire_time"))), refVal_expire_time ); + setExpireTime(refVal_expire_time); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exec_inst")))) + { + std::vector refVal_exec_inst; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exec_inst"))), refVal_exec_inst ); + setExecInst(refVal_exec_inst); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("client_order_id_format_exchange")))) + { + utility::string_t refVal_client_order_id_format_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("client_order_id_format_exchange"))), refVal_client_order_id_format_exchange ); + setClientOrderIdFormatExchange(refVal_client_order_id_format_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_order_id")))) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_order_id"))), refVal_exchange_order_id ); + setExchangeOrderId(refVal_exchange_order_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_open")))) + { + double refVal_amount_open; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_open"))), refVal_amount_open ); + setAmountOpen(refVal_amount_open); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_filled")))) + { + double refVal_amount_filled; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_filled"))), refVal_amount_filled ); + setAmountFilled(refVal_amount_filled); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("avg_px")))) + { + double refVal_avg_px; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("avg_px"))), refVal_avg_px ); + setAvgPx(refVal_avg_px); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("status")))) + { + std::shared_ptr refVal_status; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("status"))), refVal_status ); + setStatus(refVal_status); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("status_history")))) + { + std::vector> refVal_status_history; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("status_history"))), refVal_status_history ); + setStatusHistory(refVal_status_history); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("error_message")))) + { + utility::string_t refVal_error_message; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("error_message"))), refVal_error_message ); + setErrorMessage(refVal_error_message); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("fills")))) + { + std::vector> refVal_fills; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("fills"))), refVal_fills ); + setFills(refVal_fills); + } + return ok; +} + +utility::string_t OrderExecutionReport::getExchangeId() const +{ + return m_Exchange_id; +} + +void OrderExecutionReport::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool OrderExecutionReport::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void OrderExecutionReport::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +utility::string_t OrderExecutionReport::getClientOrderId() const +{ + return m_Client_order_id; +} + +void OrderExecutionReport::setClientOrderId(const utility::string_t& value) +{ + m_Client_order_id = value; + m_Client_order_idIsSet = true; +} + +bool OrderExecutionReport::clientOrderIdIsSet() const +{ + return m_Client_order_idIsSet; +} + +void OrderExecutionReport::unsetClient_order_id() +{ + m_Client_order_idIsSet = false; +} +utility::string_t OrderExecutionReport::getSymbolIdExchange() const +{ + return m_Symbol_id_exchange; +} + +void OrderExecutionReport::setSymbolIdExchange(const utility::string_t& value) +{ + m_Symbol_id_exchange = value; + m_Symbol_id_exchangeIsSet = true; +} + +bool OrderExecutionReport::symbolIdExchangeIsSet() const +{ + return m_Symbol_id_exchangeIsSet; +} + +void OrderExecutionReport::unsetSymbol_id_exchange() +{ + m_Symbol_id_exchangeIsSet = false; +} +utility::string_t OrderExecutionReport::getSymbolIdCoinapi() const +{ + return m_Symbol_id_coinapi; +} + +void OrderExecutionReport::setSymbolIdCoinapi(const utility::string_t& value) +{ + m_Symbol_id_coinapi = value; + m_Symbol_id_coinapiIsSet = true; +} + +bool OrderExecutionReport::symbolIdCoinapiIsSet() const +{ + return m_Symbol_id_coinapiIsSet; +} + +void OrderExecutionReport::unsetSymbol_id_coinapi() +{ + m_Symbol_id_coinapiIsSet = false; +} +double OrderExecutionReport::getAmountOrder() const +{ + return m_Amount_order; +} + +void OrderExecutionReport::setAmountOrder(double value) +{ + m_Amount_order = value; + m_Amount_orderIsSet = true; +} + +bool OrderExecutionReport::amountOrderIsSet() const +{ + return m_Amount_orderIsSet; +} + +void OrderExecutionReport::unsetAmount_order() +{ + m_Amount_orderIsSet = false; +} +double OrderExecutionReport::getPrice() const +{ + return m_Price; +} + +void OrderExecutionReport::setPrice(double value) +{ + m_Price = value; + m_PriceIsSet = true; +} + +bool OrderExecutionReport::priceIsSet() const +{ + return m_PriceIsSet; +} + +void OrderExecutionReport::unsetPrice() +{ + m_PriceIsSet = false; +} +std::shared_ptr OrderExecutionReport::getSide() const +{ + return m_Side; +} + +void OrderExecutionReport::setSide(const std::shared_ptr& value) +{ + m_Side = value; + m_SideIsSet = true; +} + +bool OrderExecutionReport::sideIsSet() const +{ + return m_SideIsSet; +} + +void OrderExecutionReport::unsetSide() +{ + m_SideIsSet = false; +} +std::shared_ptr OrderExecutionReport::getOrderType() const +{ + return m_Order_type; +} + +void OrderExecutionReport::setOrderType(const std::shared_ptr& value) +{ + m_Order_type = value; + m_Order_typeIsSet = true; +} + +bool OrderExecutionReport::orderTypeIsSet() const +{ + return m_Order_typeIsSet; +} + +void OrderExecutionReport::unsetOrder_type() +{ + m_Order_typeIsSet = false; +} +std::shared_ptr OrderExecutionReport::getTimeInForce() const +{ + return m_Time_in_force; +} + +void OrderExecutionReport::setTimeInForce(const std::shared_ptr& value) +{ + m_Time_in_force = value; + m_Time_in_forceIsSet = true; +} + +bool OrderExecutionReport::timeInForceIsSet() const +{ + return m_Time_in_forceIsSet; +} + +void OrderExecutionReport::unsetTime_in_force() +{ + m_Time_in_forceIsSet = false; +} +std::shared_ptr OrderExecutionReport::getExpireTime() const +{ + return m_Expire_time; +} + +void OrderExecutionReport::setExpireTime(const std::shared_ptr& value) +{ + m_Expire_time = value; + m_Expire_timeIsSet = true; +} + +bool OrderExecutionReport::expireTimeIsSet() const +{ + return m_Expire_timeIsSet; +} + +void OrderExecutionReport::unsetExpire_time() +{ + m_Expire_timeIsSet = false; +} +std::vector& OrderExecutionReport::getExecInst() +{ + return m_Exec_inst; +} + +void OrderExecutionReport::setExecInst(const std::vector& value) +{ + m_Exec_inst = value; + m_Exec_instIsSet = true; +} + +bool OrderExecutionReport::execInstIsSet() const +{ + return m_Exec_instIsSet; +} + +void OrderExecutionReport::unsetExec_inst() +{ + m_Exec_instIsSet = false; +} +utility::string_t OrderExecutionReport::getClientOrderIdFormatExchange() const +{ + return m_Client_order_id_format_exchange; +} + +void OrderExecutionReport::setClientOrderIdFormatExchange(const utility::string_t& value) +{ + m_Client_order_id_format_exchange = value; + m_Client_order_id_format_exchangeIsSet = true; +} + +bool OrderExecutionReport::clientOrderIdFormatExchangeIsSet() const +{ + return m_Client_order_id_format_exchangeIsSet; +} + +void OrderExecutionReport::unsetClient_order_id_format_exchange() +{ + m_Client_order_id_format_exchangeIsSet = false; +} +utility::string_t OrderExecutionReport::getExchangeOrderId() const +{ + return m_Exchange_order_id; +} + +void OrderExecutionReport::setExchangeOrderId(const utility::string_t& value) +{ + m_Exchange_order_id = value; + m_Exchange_order_idIsSet = true; +} + +bool OrderExecutionReport::exchangeOrderIdIsSet() const +{ + return m_Exchange_order_idIsSet; +} + +void OrderExecutionReport::unsetExchange_order_id() +{ + m_Exchange_order_idIsSet = false; +} +double OrderExecutionReport::getAmountOpen() const +{ + return m_Amount_open; +} + +void OrderExecutionReport::setAmountOpen(double value) +{ + m_Amount_open = value; + m_Amount_openIsSet = true; +} + +bool OrderExecutionReport::amountOpenIsSet() const +{ + return m_Amount_openIsSet; +} + +void OrderExecutionReport::unsetAmount_open() +{ + m_Amount_openIsSet = false; +} +double OrderExecutionReport::getAmountFilled() const +{ + return m_Amount_filled; +} + +void OrderExecutionReport::setAmountFilled(double value) +{ + m_Amount_filled = value; + m_Amount_filledIsSet = true; +} + +bool OrderExecutionReport::amountFilledIsSet() const +{ + return m_Amount_filledIsSet; +} + +void OrderExecutionReport::unsetAmount_filled() +{ + m_Amount_filledIsSet = false; +} +double OrderExecutionReport::getAvgPx() const +{ + return m_Avg_px; +} + +void OrderExecutionReport::setAvgPx(double value) +{ + m_Avg_px = value; + m_Avg_pxIsSet = true; +} + +bool OrderExecutionReport::avgPxIsSet() const +{ + return m_Avg_pxIsSet; +} + +void OrderExecutionReport::unsetAvg_px() +{ + m_Avg_pxIsSet = false; +} +std::shared_ptr OrderExecutionReport::getStatus() const +{ + return m_Status; +} + +void OrderExecutionReport::setStatus(const std::shared_ptr& value) +{ + m_Status = value; + m_StatusIsSet = true; +} + +bool OrderExecutionReport::statusIsSet() const +{ + return m_StatusIsSet; +} + +void OrderExecutionReport::unsetStatus() +{ + m_StatusIsSet = false; +} +std::vector>& OrderExecutionReport::getStatusHistory() +{ + return m_Status_history; +} + +void OrderExecutionReport::setStatusHistory(const std::vector>& value) +{ + m_Status_history = value; + m_Status_historyIsSet = true; +} + +bool OrderExecutionReport::statusHistoryIsSet() const +{ + return m_Status_historyIsSet; +} + +void OrderExecutionReport::unsetStatus_history() +{ + m_Status_historyIsSet = false; +} +utility::string_t OrderExecutionReport::getErrorMessage() const +{ + return m_Error_message; +} + +void OrderExecutionReport::setErrorMessage(const utility::string_t& value) +{ + m_Error_message = value; + m_Error_messageIsSet = true; +} + +bool OrderExecutionReport::errorMessageIsSet() const +{ + return m_Error_messageIsSet; +} + +void OrderExecutionReport::unsetError_message() +{ + m_Error_messageIsSet = false; +} +std::vector>& OrderExecutionReport::getFills() +{ + return m_Fills; +} + +void OrderExecutionReport::setFills(const std::vector>& value) +{ + m_Fills = value; + m_FillsIsSet = true; +} + +bool OrderExecutionReport::fillsIsSet() const +{ + return m_FillsIsSet; +} + +void OrderExecutionReport::unsetFills() +{ + m_FillsIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.h new file mode 100644 index 0000000000..13696bab2f --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport.h @@ -0,0 +1,295 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrderExecutionReport.h + * + * The order execution report object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_H_ + + +#include "ModelBase.h" + +#include "model/TimeInForce.h" +#include "model/OrderExecutionReport_allOf.h" +#include "model/OrdSide.h" +#include "model/OrderNewSingleRequest.h" +#include +#include "model/Fills.h" +#include "model/OrdStatus.h" +#include "model/OrdType.h" +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// The order execution report object. +/// +class OrderExecutionReport + : public ModelBase +{ +public: + OrderExecutionReport(); + virtual ~OrderExecutionReport(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// OrderExecutionReport members + + /// + /// Exchange identifier used to identify the routing destination. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// The unique identifier of the order assigned by the client. + /// + utility::string_t getClientOrderId() const; + bool clientOrderIdIsSet() const; + void unsetClient_order_id(); + + void setClientOrderId(const utility::string_t& value); + + /// + /// Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + /// + utility::string_t getSymbolIdExchange() const; + bool symbolIdExchangeIsSet() const; + void unsetSymbol_id_exchange(); + + void setSymbolIdExchange(const utility::string_t& value); + + /// + /// CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + /// + utility::string_t getSymbolIdCoinapi() const; + bool symbolIdCoinapiIsSet() const; + void unsetSymbol_id_coinapi(); + + void setSymbolIdCoinapi(const utility::string_t& value); + + /// + /// Order quantity. + /// + double getAmountOrder() const; + bool amountOrderIsSet() const; + void unsetAmount_order(); + + void setAmountOrder(double value); + + /// + /// Order price. + /// + double getPrice() const; + bool priceIsSet() const; + void unsetPrice(); + + void setPrice(double value); + + /// + /// + /// + std::shared_ptr getSide() const; + bool sideIsSet() const; + void unsetSide(); + + void setSide(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getOrderType() const; + bool orderTypeIsSet() const; + void unsetOrder_type(); + + void setOrderType(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getTimeInForce() const; + bool timeInForceIsSet() const; + void unsetTime_in_force(); + + void setTimeInForce(const std::shared_ptr& value); + + /// + /// Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + /// + std::shared_ptr getExpireTime() const; + bool expireTimeIsSet() const; + void unsetExpire_time(); + + void setExpireTime(const std::shared_ptr& value); + + /// + /// Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> + /// + std::vector& getExecInst(); + bool execInstIsSet() const; + void unsetExec_inst(); + + void setExecInst(const std::vector& value); + + /// + /// The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + /// + utility::string_t getClientOrderIdFormatExchange() const; + bool clientOrderIdFormatExchangeIsSet() const; + void unsetClient_order_id_format_exchange(); + + void setClientOrderIdFormatExchange(const utility::string_t& value); + + /// + /// Unique identifier of the order assigned by the exchange or executing system. + /// + utility::string_t getExchangeOrderId() const; + bool exchangeOrderIdIsSet() const; + void unsetExchange_order_id(); + + void setExchangeOrderId(const utility::string_t& value); + + /// + /// Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + /// + double getAmountOpen() const; + bool amountOpenIsSet() const; + void unsetAmount_open(); + + void setAmountOpen(double value); + + /// + /// Total quantity filled. + /// + double getAmountFilled() const; + bool amountFilledIsSet() const; + void unsetAmount_filled(); + + void setAmountFilled(double value); + + /// + /// Calculated average price of all fills on this order. + /// + double getAvgPx() const; + bool avgPxIsSet() const; + void unsetAvg_px(); + + void setAvgPx(double value); + + /// + /// + /// + std::shared_ptr getStatus() const; + bool statusIsSet() const; + void unsetStatus(); + + void setStatus(const std::shared_ptr& value); + + /// + /// Timestamped history of order status changes. + /// + std::vector>& getStatusHistory(); + bool statusHistoryIsSet() const; + void unsetStatus_history(); + + void setStatusHistory(const std::vector>& value); + + /// + /// Error message. + /// + utility::string_t getErrorMessage() const; + bool errorMessageIsSet() const; + void unsetError_message(); + + void setErrorMessage(const utility::string_t& value); + + /// + /// Relay fill information on working orders. + /// + std::vector>& getFills(); + bool fillsIsSet() const; + void unsetFills(); + + void setFills(const std::vector>& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + utility::string_t m_Client_order_id; + bool m_Client_order_idIsSet; + utility::string_t m_Symbol_id_exchange; + bool m_Symbol_id_exchangeIsSet; + utility::string_t m_Symbol_id_coinapi; + bool m_Symbol_id_coinapiIsSet; + double m_Amount_order; + bool m_Amount_orderIsSet; + double m_Price; + bool m_PriceIsSet; + std::shared_ptr m_Side; + bool m_SideIsSet; + std::shared_ptr m_Order_type; + bool m_Order_typeIsSet; + std::shared_ptr m_Time_in_force; + bool m_Time_in_forceIsSet; + std::shared_ptr m_Expire_time; + bool m_Expire_timeIsSet; + std::vector m_Exec_inst; + bool m_Exec_instIsSet; + utility::string_t m_Client_order_id_format_exchange; + bool m_Client_order_id_format_exchangeIsSet; + utility::string_t m_Exchange_order_id; + bool m_Exchange_order_idIsSet; + double m_Amount_open; + bool m_Amount_openIsSet; + double m_Amount_filled; + bool m_Amount_filledIsSet; + double m_Avg_px; + bool m_Avg_pxIsSet; + std::shared_ptr m_Status; + bool m_StatusIsSet; + std::vector> m_Status_history; + bool m_Status_historyIsSet; + utility::string_t m_Error_message; + bool m_Error_messageIsSet; + std::vector> m_Fills; + bool m_FillsIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.cpp new file mode 100644 index 0000000000..92ae010a82 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.cpp @@ -0,0 +1,491 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrderExecutionReport_allOf.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +OrderExecutionReport_allOf::OrderExecutionReport_allOf() +{ + m_Client_order_id_format_exchange = utility::conversions::to_string_t(""); + m_Client_order_id_format_exchangeIsSet = false; + m_Exchange_order_id = utility::conversions::to_string_t(""); + m_Exchange_order_idIsSet = false; + m_Amount_open = 0.0; + m_Amount_openIsSet = false; + m_Amount_filled = 0.0; + m_Amount_filledIsSet = false; + m_Avg_px = 0.0; + m_Avg_pxIsSet = false; + m_StatusIsSet = false; + m_Status_historyIsSet = false; + m_Error_message = utility::conversions::to_string_t(""); + m_Error_messageIsSet = false; + m_FillsIsSet = false; +} + +OrderExecutionReport_allOf::~OrderExecutionReport_allOf() +{ +} + +void OrderExecutionReport_allOf::validate() +{ + // TODO: implement validation +} + +web::json::value OrderExecutionReport_allOf::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Client_order_id_format_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("client_order_id_format_exchange"))] = ModelBase::toJson(m_Client_order_id_format_exchange); + } + if(m_Exchange_order_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_order_id"))] = ModelBase::toJson(m_Exchange_order_id); + } + if(m_Amount_openIsSet) + { + val[utility::conversions::to_string_t(U("amount_open"))] = ModelBase::toJson(m_Amount_open); + } + if(m_Amount_filledIsSet) + { + val[utility::conversions::to_string_t(U("amount_filled"))] = ModelBase::toJson(m_Amount_filled); + } + if(m_Avg_pxIsSet) + { + val[utility::conversions::to_string_t(U("avg_px"))] = ModelBase::toJson(m_Avg_px); + } + if(m_StatusIsSet) + { + val[utility::conversions::to_string_t(U("status"))] = ModelBase::toJson(m_Status); + } + if(m_Status_historyIsSet) + { + val[utility::conversions::to_string_t(U("status_history"))] = ModelBase::toJson(m_Status_history); + } + if(m_Error_messageIsSet) + { + val[utility::conversions::to_string_t(U("error_message"))] = ModelBase::toJson(m_Error_message); + } + if(m_FillsIsSet) + { + val[utility::conversions::to_string_t(U("fills"))] = ModelBase::toJson(m_Fills); + } + + return val; +} + +bool OrderExecutionReport_allOf::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("client_order_id_format_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("client_order_id_format_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_client_order_id_format_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_client_order_id_format_exchange); + setClientOrderIdFormatExchange(refVal_client_order_id_format_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exchange_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_order_id); + setExchangeOrderId(refVal_exchange_order_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_open")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_open"))); + if(!fieldValue.is_null()) + { + double refVal_amount_open; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_open); + setAmountOpen(refVal_amount_open); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_filled")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_filled"))); + if(!fieldValue.is_null()) + { + double refVal_amount_filled; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_filled); + setAmountFilled(refVal_amount_filled); + } + } + if(val.has_field(utility::conversions::to_string_t(U("avg_px")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("avg_px"))); + if(!fieldValue.is_null()) + { + double refVal_avg_px; + ok &= ModelBase::fromJson(fieldValue, refVal_avg_px); + setAvgPx(refVal_avg_px); + } + } + if(val.has_field(utility::conversions::to_string_t(U("status")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("status"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_status; + ok &= ModelBase::fromJson(fieldValue, refVal_status); + setStatus(refVal_status); + } + } + if(val.has_field(utility::conversions::to_string_t(U("status_history")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("status_history"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_status_history; + ok &= ModelBase::fromJson(fieldValue, refVal_status_history); + setStatusHistory(refVal_status_history); + } + } + if(val.has_field(utility::conversions::to_string_t(U("error_message")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("error_message"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_error_message; + ok &= ModelBase::fromJson(fieldValue, refVal_error_message); + setErrorMessage(refVal_error_message); + } + } + if(val.has_field(utility::conversions::to_string_t(U("fills")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("fills"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_fills; + ok &= ModelBase::fromJson(fieldValue, refVal_fills); + setFills(refVal_fills); + } + } + return ok; +} + +void OrderExecutionReport_allOf::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Client_order_id_format_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("client_order_id_format_exchange")), m_Client_order_id_format_exchange)); + } + if(m_Exchange_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_order_id")), m_Exchange_order_id)); + } + if(m_Amount_openIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_open")), m_Amount_open)); + } + if(m_Amount_filledIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_filled")), m_Amount_filled)); + } + if(m_Avg_pxIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("avg_px")), m_Avg_px)); + } + if(m_StatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("status")), m_Status)); + } + if(m_Status_historyIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("status_history")), m_Status_history)); + } + if(m_Error_messageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("error_message")), m_Error_message)); + } + if(m_FillsIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("fills")), m_Fills)); + } +} + +bool OrderExecutionReport_allOf::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("client_order_id_format_exchange")))) + { + utility::string_t refVal_client_order_id_format_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("client_order_id_format_exchange"))), refVal_client_order_id_format_exchange ); + setClientOrderIdFormatExchange(refVal_client_order_id_format_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_order_id")))) + { + utility::string_t refVal_exchange_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_order_id"))), refVal_exchange_order_id ); + setExchangeOrderId(refVal_exchange_order_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_open")))) + { + double refVal_amount_open; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_open"))), refVal_amount_open ); + setAmountOpen(refVal_amount_open); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_filled")))) + { + double refVal_amount_filled; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_filled"))), refVal_amount_filled ); + setAmountFilled(refVal_amount_filled); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("avg_px")))) + { + double refVal_avg_px; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("avg_px"))), refVal_avg_px ); + setAvgPx(refVal_avg_px); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("status")))) + { + std::shared_ptr refVal_status; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("status"))), refVal_status ); + setStatus(refVal_status); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("status_history")))) + { + std::vector> refVal_status_history; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("status_history"))), refVal_status_history ); + setStatusHistory(refVal_status_history); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("error_message")))) + { + utility::string_t refVal_error_message; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("error_message"))), refVal_error_message ); + setErrorMessage(refVal_error_message); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("fills")))) + { + std::vector> refVal_fills; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("fills"))), refVal_fills ); + setFills(refVal_fills); + } + return ok; +} + +utility::string_t OrderExecutionReport_allOf::getClientOrderIdFormatExchange() const +{ + return m_Client_order_id_format_exchange; +} + +void OrderExecutionReport_allOf::setClientOrderIdFormatExchange(const utility::string_t& value) +{ + m_Client_order_id_format_exchange = value; + m_Client_order_id_format_exchangeIsSet = true; +} + +bool OrderExecutionReport_allOf::clientOrderIdFormatExchangeIsSet() const +{ + return m_Client_order_id_format_exchangeIsSet; +} + +void OrderExecutionReport_allOf::unsetClient_order_id_format_exchange() +{ + m_Client_order_id_format_exchangeIsSet = false; +} +utility::string_t OrderExecutionReport_allOf::getExchangeOrderId() const +{ + return m_Exchange_order_id; +} + +void OrderExecutionReport_allOf::setExchangeOrderId(const utility::string_t& value) +{ + m_Exchange_order_id = value; + m_Exchange_order_idIsSet = true; +} + +bool OrderExecutionReport_allOf::exchangeOrderIdIsSet() const +{ + return m_Exchange_order_idIsSet; +} + +void OrderExecutionReport_allOf::unsetExchange_order_id() +{ + m_Exchange_order_idIsSet = false; +} +double OrderExecutionReport_allOf::getAmountOpen() const +{ + return m_Amount_open; +} + +void OrderExecutionReport_allOf::setAmountOpen(double value) +{ + m_Amount_open = value; + m_Amount_openIsSet = true; +} + +bool OrderExecutionReport_allOf::amountOpenIsSet() const +{ + return m_Amount_openIsSet; +} + +void OrderExecutionReport_allOf::unsetAmount_open() +{ + m_Amount_openIsSet = false; +} +double OrderExecutionReport_allOf::getAmountFilled() const +{ + return m_Amount_filled; +} + +void OrderExecutionReport_allOf::setAmountFilled(double value) +{ + m_Amount_filled = value; + m_Amount_filledIsSet = true; +} + +bool OrderExecutionReport_allOf::amountFilledIsSet() const +{ + return m_Amount_filledIsSet; +} + +void OrderExecutionReport_allOf::unsetAmount_filled() +{ + m_Amount_filledIsSet = false; +} +double OrderExecutionReport_allOf::getAvgPx() const +{ + return m_Avg_px; +} + +void OrderExecutionReport_allOf::setAvgPx(double value) +{ + m_Avg_px = value; + m_Avg_pxIsSet = true; +} + +bool OrderExecutionReport_allOf::avgPxIsSet() const +{ + return m_Avg_pxIsSet; +} + +void OrderExecutionReport_allOf::unsetAvg_px() +{ + m_Avg_pxIsSet = false; +} +std::shared_ptr OrderExecutionReport_allOf::getStatus() const +{ + return m_Status; +} + +void OrderExecutionReport_allOf::setStatus(const std::shared_ptr& value) +{ + m_Status = value; + m_StatusIsSet = true; +} + +bool OrderExecutionReport_allOf::statusIsSet() const +{ + return m_StatusIsSet; +} + +void OrderExecutionReport_allOf::unsetStatus() +{ + m_StatusIsSet = false; +} +std::vector>& OrderExecutionReport_allOf::getStatusHistory() +{ + return m_Status_history; +} + +void OrderExecutionReport_allOf::setStatusHistory(const std::vector>& value) +{ + m_Status_history = value; + m_Status_historyIsSet = true; +} + +bool OrderExecutionReport_allOf::statusHistoryIsSet() const +{ + return m_Status_historyIsSet; +} + +void OrderExecutionReport_allOf::unsetStatus_history() +{ + m_Status_historyIsSet = false; +} +utility::string_t OrderExecutionReport_allOf::getErrorMessage() const +{ + return m_Error_message; +} + +void OrderExecutionReport_allOf::setErrorMessage(const utility::string_t& value) +{ + m_Error_message = value; + m_Error_messageIsSet = true; +} + +bool OrderExecutionReport_allOf::errorMessageIsSet() const +{ + return m_Error_messageIsSet; +} + +void OrderExecutionReport_allOf::unsetError_message() +{ + m_Error_messageIsSet = false; +} +std::vector>& OrderExecutionReport_allOf::getFills() +{ + return m_Fills; +} + +void OrderExecutionReport_allOf::setFills(const std::vector>& value) +{ + m_Fills = value; + m_FillsIsSet = true; +} + +bool OrderExecutionReport_allOf::fillsIsSet() const +{ + return m_FillsIsSet; +} + +void OrderExecutionReport_allOf::unsetFills() +{ + m_FillsIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.h new file mode 100644 index 0000000000..c6f676a045 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderExecutionReport_allOf.h @@ -0,0 +1,169 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrderExecutionReport_allOf.h + * + * The order execution report message. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_allOf_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_allOf_H_ + + +#include "ModelBase.h" + +#include +#include "model/Fills.h" +#include "model/OrdStatus.h" +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// The order execution report message. +/// +class OrderExecutionReport_allOf + : public ModelBase +{ +public: + OrderExecutionReport_allOf(); + virtual ~OrderExecutionReport_allOf(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// OrderExecutionReport_allOf members + + /// + /// The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. + /// + utility::string_t getClientOrderIdFormatExchange() const; + bool clientOrderIdFormatExchangeIsSet() const; + void unsetClient_order_id_format_exchange(); + + void setClientOrderIdFormatExchange(const utility::string_t& value); + + /// + /// Unique identifier of the order assigned by the exchange or executing system. + /// + utility::string_t getExchangeOrderId() const; + bool exchangeOrderIdIsSet() const; + void unsetExchange_order_id(); + + void setExchangeOrderId(const utility::string_t& value); + + /// + /// Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` + /// + double getAmountOpen() const; + bool amountOpenIsSet() const; + void unsetAmount_open(); + + void setAmountOpen(double value); + + /// + /// Total quantity filled. + /// + double getAmountFilled() const; + bool amountFilledIsSet() const; + void unsetAmount_filled(); + + void setAmountFilled(double value); + + /// + /// Calculated average price of all fills on this order. + /// + double getAvgPx() const; + bool avgPxIsSet() const; + void unsetAvg_px(); + + void setAvgPx(double value); + + /// + /// + /// + std::shared_ptr getStatus() const; + bool statusIsSet() const; + void unsetStatus(); + + void setStatus(const std::shared_ptr& value); + + /// + /// Timestamped history of order status changes. + /// + std::vector>& getStatusHistory(); + bool statusHistoryIsSet() const; + void unsetStatus_history(); + + void setStatusHistory(const std::vector>& value); + + /// + /// Error message. + /// + utility::string_t getErrorMessage() const; + bool errorMessageIsSet() const; + void unsetError_message(); + + void setErrorMessage(const utility::string_t& value); + + /// + /// Relay fill information on working orders. + /// + std::vector>& getFills(); + bool fillsIsSet() const; + void unsetFills(); + + void setFills(const std::vector>& value); + + +protected: + utility::string_t m_Client_order_id_format_exchange; + bool m_Client_order_id_format_exchangeIsSet; + utility::string_t m_Exchange_order_id; + bool m_Exchange_order_idIsSet; + double m_Amount_open; + bool m_Amount_openIsSet; + double m_Amount_filled; + bool m_Amount_filledIsSet; + double m_Avg_px; + bool m_Avg_pxIsSet; + std::shared_ptr m_Status; + bool m_StatusIsSet; + std::vector> m_Status_history; + bool m_Status_historyIsSet; + utility::string_t m_Error_message; + bool m_Error_messageIsSet; + std::vector> m_Fills; + bool m_FillsIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrderExecutionReport_allOf_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.cpp new file mode 100644 index 0000000000..d3996fd481 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.cpp @@ -0,0 +1,581 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OrderNewSingleRequest.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +OrderNewSingleRequest::OrderNewSingleRequest() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_Client_order_id = utility::conversions::to_string_t(""); + m_Client_order_idIsSet = false; + m_Symbol_id_exchange = utility::conversions::to_string_t(""); + m_Symbol_id_exchangeIsSet = false; + m_Symbol_id_coinapi = utility::conversions::to_string_t(""); + m_Symbol_id_coinapiIsSet = false; + m_Amount_order = 0.0; + m_Amount_orderIsSet = false; + m_Price = 0.0; + m_PriceIsSet = false; + m_SideIsSet = false; + m_Order_typeIsSet = false; + m_Time_in_forceIsSet = false; + m_Expire_timeIsSet = false; + m_Exec_instIsSet = false; +} + +OrderNewSingleRequest::~OrderNewSingleRequest() +{ +} + +void OrderNewSingleRequest::validate() +{ + // TODO: implement validation +} + +web::json::value OrderNewSingleRequest::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_Client_order_idIsSet) + { + val[utility::conversions::to_string_t(U("client_order_id"))] = ModelBase::toJson(m_Client_order_id); + } + if(m_Symbol_id_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_exchange"))] = ModelBase::toJson(m_Symbol_id_exchange); + } + if(m_Symbol_id_coinapiIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_coinapi"))] = ModelBase::toJson(m_Symbol_id_coinapi); + } + if(m_Amount_orderIsSet) + { + val[utility::conversions::to_string_t(U("amount_order"))] = ModelBase::toJson(m_Amount_order); + } + if(m_PriceIsSet) + { + val[utility::conversions::to_string_t(U("price"))] = ModelBase::toJson(m_Price); + } + if(m_SideIsSet) + { + val[utility::conversions::to_string_t(U("side"))] = ModelBase::toJson(m_Side); + } + if(m_Order_typeIsSet) + { + val[utility::conversions::to_string_t(U("order_type"))] = ModelBase::toJson(m_Order_type); + } + if(m_Time_in_forceIsSet) + { + val[utility::conversions::to_string_t(U("time_in_force"))] = ModelBase::toJson(m_Time_in_force); + } + if(m_Expire_timeIsSet) + { + val[utility::conversions::to_string_t(U("expire_time"))] = ModelBase::toJson(m_Expire_time); + } + if(m_Exec_instIsSet) + { + val[utility::conversions::to_string_t(U("exec_inst"))] = ModelBase::toJson(m_Exec_inst); + } + + return val; +} + +bool OrderNewSingleRequest::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("client_order_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("client_order_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromJson(fieldValue, refVal_client_order_id); + setClientOrderId(refVal_client_order_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_exchange); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_coinapi"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_coinapi); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + } + if(val.has_field(utility::conversions::to_string_t(U("amount_order")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("amount_order"))); + if(!fieldValue.is_null()) + { + double refVal_amount_order; + ok &= ModelBase::fromJson(fieldValue, refVal_amount_order); + setAmountOrder(refVal_amount_order); + } + } + if(val.has_field(utility::conversions::to_string_t(U("price")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("price"))); + if(!fieldValue.is_null()) + { + double refVal_price; + ok &= ModelBase::fromJson(fieldValue, refVal_price); + setPrice(refVal_price); + } + } + if(val.has_field(utility::conversions::to_string_t(U("side")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("side"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromJson(fieldValue, refVal_side); + setSide(refVal_side); + } + } + if(val.has_field(utility::conversions::to_string_t(U("order_type")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("order_type"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_order_type; + ok &= ModelBase::fromJson(fieldValue, refVal_order_type); + setOrderType(refVal_order_type); + } + } + if(val.has_field(utility::conversions::to_string_t(U("time_in_force")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("time_in_force"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_time_in_force; + ok &= ModelBase::fromJson(fieldValue, refVal_time_in_force); + setTimeInForce(refVal_time_in_force); + } + } + if(val.has_field(utility::conversions::to_string_t(U("expire_time")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("expire_time"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_expire_time; + ok &= ModelBase::fromJson(fieldValue, refVal_expire_time); + setExpireTime(refVal_expire_time); + } + } + if(val.has_field(utility::conversions::to_string_t(U("exec_inst")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exec_inst"))); + if(!fieldValue.is_null()) + { + std::vector refVal_exec_inst; + ok &= ModelBase::fromJson(fieldValue, refVal_exec_inst); + setExecInst(refVal_exec_inst); + } + } + return ok; +} + +void OrderNewSingleRequest::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_Client_order_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("client_order_id")), m_Client_order_id)); + } + if(m_Symbol_id_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_exchange")), m_Symbol_id_exchange)); + } + if(m_Symbol_id_coinapiIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_coinapi")), m_Symbol_id_coinapi)); + } + if(m_Amount_orderIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("amount_order")), m_Amount_order)); + } + if(m_PriceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("price")), m_Price)); + } + if(m_SideIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("side")), m_Side)); + } + if(m_Order_typeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("order_type")), m_Order_type)); + } + if(m_Time_in_forceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("time_in_force")), m_Time_in_force)); + } + if(m_Expire_timeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("expire_time")), m_Expire_time)); + } + if(m_Exec_instIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exec_inst")), m_Exec_inst)); + } +} + +bool OrderNewSingleRequest::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("client_order_id")))) + { + utility::string_t refVal_client_order_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("client_order_id"))), refVal_client_order_id ); + setClientOrderId(refVal_client_order_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_exchange"))), refVal_symbol_id_exchange ); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_coinapi"))), refVal_symbol_id_coinapi ); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("amount_order")))) + { + double refVal_amount_order; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("amount_order"))), refVal_amount_order ); + setAmountOrder(refVal_amount_order); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("price")))) + { + double refVal_price; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("price"))), refVal_price ); + setPrice(refVal_price); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("side")))) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("side"))), refVal_side ); + setSide(refVal_side); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("order_type")))) + { + std::shared_ptr refVal_order_type; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("order_type"))), refVal_order_type ); + setOrderType(refVal_order_type); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("time_in_force")))) + { + std::shared_ptr refVal_time_in_force; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("time_in_force"))), refVal_time_in_force ); + setTimeInForce(refVal_time_in_force); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("expire_time")))) + { + std::shared_ptr refVal_expire_time; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("expire_time"))), refVal_expire_time ); + setExpireTime(refVal_expire_time); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("exec_inst")))) + { + std::vector refVal_exec_inst; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exec_inst"))), refVal_exec_inst ); + setExecInst(refVal_exec_inst); + } + return ok; +} + +utility::string_t OrderNewSingleRequest::getExchangeId() const +{ + return m_Exchange_id; +} + +void OrderNewSingleRequest::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool OrderNewSingleRequest::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void OrderNewSingleRequest::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +utility::string_t OrderNewSingleRequest::getClientOrderId() const +{ + return m_Client_order_id; +} + +void OrderNewSingleRequest::setClientOrderId(const utility::string_t& value) +{ + m_Client_order_id = value; + m_Client_order_idIsSet = true; +} + +bool OrderNewSingleRequest::clientOrderIdIsSet() const +{ + return m_Client_order_idIsSet; +} + +void OrderNewSingleRequest::unsetClient_order_id() +{ + m_Client_order_idIsSet = false; +} +utility::string_t OrderNewSingleRequest::getSymbolIdExchange() const +{ + return m_Symbol_id_exchange; +} + +void OrderNewSingleRequest::setSymbolIdExchange(const utility::string_t& value) +{ + m_Symbol_id_exchange = value; + m_Symbol_id_exchangeIsSet = true; +} + +bool OrderNewSingleRequest::symbolIdExchangeIsSet() const +{ + return m_Symbol_id_exchangeIsSet; +} + +void OrderNewSingleRequest::unsetSymbol_id_exchange() +{ + m_Symbol_id_exchangeIsSet = false; +} +utility::string_t OrderNewSingleRequest::getSymbolIdCoinapi() const +{ + return m_Symbol_id_coinapi; +} + +void OrderNewSingleRequest::setSymbolIdCoinapi(const utility::string_t& value) +{ + m_Symbol_id_coinapi = value; + m_Symbol_id_coinapiIsSet = true; +} + +bool OrderNewSingleRequest::symbolIdCoinapiIsSet() const +{ + return m_Symbol_id_coinapiIsSet; +} + +void OrderNewSingleRequest::unsetSymbol_id_coinapi() +{ + m_Symbol_id_coinapiIsSet = false; +} +double OrderNewSingleRequest::getAmountOrder() const +{ + return m_Amount_order; +} + +void OrderNewSingleRequest::setAmountOrder(double value) +{ + m_Amount_order = value; + m_Amount_orderIsSet = true; +} + +bool OrderNewSingleRequest::amountOrderIsSet() const +{ + return m_Amount_orderIsSet; +} + +void OrderNewSingleRequest::unsetAmount_order() +{ + m_Amount_orderIsSet = false; +} +double OrderNewSingleRequest::getPrice() const +{ + return m_Price; +} + +void OrderNewSingleRequest::setPrice(double value) +{ + m_Price = value; + m_PriceIsSet = true; +} + +bool OrderNewSingleRequest::priceIsSet() const +{ + return m_PriceIsSet; +} + +void OrderNewSingleRequest::unsetPrice() +{ + m_PriceIsSet = false; +} +std::shared_ptr OrderNewSingleRequest::getSide() const +{ + return m_Side; +} + +void OrderNewSingleRequest::setSide(const std::shared_ptr& value) +{ + m_Side = value; + m_SideIsSet = true; +} + +bool OrderNewSingleRequest::sideIsSet() const +{ + return m_SideIsSet; +} + +void OrderNewSingleRequest::unsetSide() +{ + m_SideIsSet = false; +} +std::shared_ptr OrderNewSingleRequest::getOrderType() const +{ + return m_Order_type; +} + +void OrderNewSingleRequest::setOrderType(const std::shared_ptr& value) +{ + m_Order_type = value; + m_Order_typeIsSet = true; +} + +bool OrderNewSingleRequest::orderTypeIsSet() const +{ + return m_Order_typeIsSet; +} + +void OrderNewSingleRequest::unsetOrder_type() +{ + m_Order_typeIsSet = false; +} +std::shared_ptr OrderNewSingleRequest::getTimeInForce() const +{ + return m_Time_in_force; +} + +void OrderNewSingleRequest::setTimeInForce(const std::shared_ptr& value) +{ + m_Time_in_force = value; + m_Time_in_forceIsSet = true; +} + +bool OrderNewSingleRequest::timeInForceIsSet() const +{ + return m_Time_in_forceIsSet; +} + +void OrderNewSingleRequest::unsetTime_in_force() +{ + m_Time_in_forceIsSet = false; +} +std::shared_ptr OrderNewSingleRequest::getExpireTime() const +{ + return m_Expire_time; +} + +void OrderNewSingleRequest::setExpireTime(const std::shared_ptr& value) +{ + m_Expire_time = value; + m_Expire_timeIsSet = true; +} + +bool OrderNewSingleRequest::expireTimeIsSet() const +{ + return m_Expire_timeIsSet; +} + +void OrderNewSingleRequest::unsetExpire_time() +{ + m_Expire_timeIsSet = false; +} +std::vector& OrderNewSingleRequest::getExecInst() +{ + return m_Exec_inst; +} + +void OrderNewSingleRequest::setExecInst(const std::vector& value) +{ + m_Exec_inst = value; + m_Exec_instIsSet = true; +} + +bool OrderNewSingleRequest::execInstIsSet() const +{ + return m_Exec_instIsSet; +} + +void OrderNewSingleRequest::unsetExec_inst() +{ + m_Exec_instIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.h new file mode 100644 index 0000000000..7e65a921c4 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/OrderNewSingleRequest.h @@ -0,0 +1,192 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OrderNewSingleRequest.h + * + * The new order message. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_OrderNewSingleRequest_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_OrderNewSingleRequest_H_ + + +#include "ModelBase.h" + +#include "model/TimeInForce.h" +#include "model/OrdSide.h" +#include +#include "model/OrdType.h" +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// The new order message. +/// +class OrderNewSingleRequest + : public ModelBase +{ +public: + OrderNewSingleRequest(); + virtual ~OrderNewSingleRequest(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// OrderNewSingleRequest members + + /// + /// Exchange identifier used to identify the routing destination. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// The unique identifier of the order assigned by the client. + /// + utility::string_t getClientOrderId() const; + bool clientOrderIdIsSet() const; + void unsetClient_order_id(); + + void setClientOrderId(const utility::string_t& value); + + /// + /// Exchange symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + /// + utility::string_t getSymbolIdExchange() const; + bool symbolIdExchangeIsSet() const; + void unsetSymbol_id_exchange(); + + void setSymbolIdExchange(const utility::string_t& value); + + /// + /// CoinAPI symbol. One of the properties (`symbol_id_exchange`, `symbol_id_coinapi`) is required to identify the market for the new order. + /// + utility::string_t getSymbolIdCoinapi() const; + bool symbolIdCoinapiIsSet() const; + void unsetSymbol_id_coinapi(); + + void setSymbolIdCoinapi(const utility::string_t& value); + + /// + /// Order quantity. + /// + double getAmountOrder() const; + bool amountOrderIsSet() const; + void unsetAmount_order(); + + void setAmountOrder(double value); + + /// + /// Order price. + /// + double getPrice() const; + bool priceIsSet() const; + void unsetPrice(); + + void setPrice(double value); + + /// + /// + /// + std::shared_ptr getSide() const; + bool sideIsSet() const; + void unsetSide(); + + void setSide(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getOrderType() const; + bool orderTypeIsSet() const; + void unsetOrder_type(); + + void setOrderType(const std::shared_ptr& value); + + /// + /// + /// + std::shared_ptr getTimeInForce() const; + bool timeInForceIsSet() const; + void unsetTime_in_force(); + + void setTimeInForce(const std::shared_ptr& value); + + /// + /// Expiration time. Conditionaly required for orders with time_in_force = `GOOD_TILL_TIME_EXCHANGE` or `GOOD_TILL_TIME_OEML`. + /// + std::shared_ptr getExpireTime() const; + bool expireTimeIsSet() const; + void unsetExpire_time(); + + void setExpireTime(const std::shared_ptr& value); + + /// + /// Order execution instructions are documented in the separate section: <a href=\"#ems-order-params-exec\">EMS / Starter Guide / Order parameters / Execution instructions</a> + /// + std::vector& getExecInst(); + bool execInstIsSet() const; + void unsetExec_inst(); + + void setExecInst(const std::vector& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + utility::string_t m_Client_order_id; + bool m_Client_order_idIsSet; + utility::string_t m_Symbol_id_exchange; + bool m_Symbol_id_exchangeIsSet; + utility::string_t m_Symbol_id_coinapi; + bool m_Symbol_id_coinapiIsSet; + double m_Amount_order; + bool m_Amount_orderIsSet; + double m_Price; + bool m_PriceIsSet; + std::shared_ptr m_Side; + bool m_SideIsSet; + std::shared_ptr m_Order_type; + bool m_Order_typeIsSet; + std::shared_ptr m_Time_in_force; + bool m_Time_in_forceIsSet; + std::shared_ptr m_Expire_time; + bool m_Expire_timeIsSet; + std::vector m_Exec_inst; + bool m_Exec_instIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_OrderNewSingleRequest_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.cpp new file mode 100644 index 0000000000..4f9a766612 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.cpp @@ -0,0 +1,171 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Position.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +Position::Position() +{ + m_Exchange_id = utility::conversions::to_string_t(""); + m_Exchange_idIsSet = false; + m_DataIsSet = false; +} + +Position::~Position() +{ +} + +void Position::validate() +{ + // TODO: implement validation +} + +web::json::value Position::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Exchange_idIsSet) + { + val[utility::conversions::to_string_t(U("exchange_id"))] = ModelBase::toJson(m_Exchange_id); + } + if(m_DataIsSet) + { + val[utility::conversions::to_string_t(U("data"))] = ModelBase::toJson(m_Data); + } + + return val; +} + +bool Position::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("exchange_id")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("exchange_id"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromJson(fieldValue, refVal_exchange_id); + setExchangeId(refVal_exchange_id); + } + } + if(val.has_field(utility::conversions::to_string_t(U("data")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("data"))); + if(!fieldValue.is_null()) + { + std::vector> refVal_data; + ok &= ModelBase::fromJson(fieldValue, refVal_data); + setData(refVal_data); + } + } + return ok; +} + +void Position::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Exchange_idIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("exchange_id")), m_Exchange_id)); + } + if(m_DataIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("data")), m_Data)); + } +} + +bool Position::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("exchange_id")))) + { + utility::string_t refVal_exchange_id; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("exchange_id"))), refVal_exchange_id ); + setExchangeId(refVal_exchange_id); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("data")))) + { + std::vector> refVal_data; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("data"))), refVal_data ); + setData(refVal_data); + } + return ok; +} + +utility::string_t Position::getExchangeId() const +{ + return m_Exchange_id; +} + +void Position::setExchangeId(const utility::string_t& value) +{ + m_Exchange_id = value; + m_Exchange_idIsSet = true; +} + +bool Position::exchangeIdIsSet() const +{ + return m_Exchange_idIsSet; +} + +void Position::unsetExchange_id() +{ + m_Exchange_idIsSet = false; +} +std::vector>& Position::getData() +{ + return m_Data; +} + +void Position::setData(const std::vector>& value) +{ + m_Data = value; + m_DataIsSet = true; +} + +bool Position::dataIsSet() const +{ + return m_DataIsSet; +} + +void Position::unsetData() +{ + m_DataIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.h new file mode 100644 index 0000000000..22a421fd34 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position.h @@ -0,0 +1,91 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Position.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Position_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Position_H_ + + +#include "ModelBase.h" + +#include "model/Position_data.h" +#include +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class Position + : public ModelBase +{ +public: + Position(); + virtual ~Position(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Position members + + /// + /// Exchange identifier used to identify the routing destination. + /// + utility::string_t getExchangeId() const; + bool exchangeIdIsSet() const; + void unsetExchange_id(); + + void setExchangeId(const utility::string_t& value); + + /// + /// + /// + std::vector>& getData(); + bool dataIsSet() const; + void unsetData(); + + void setData(const std::vector>& value); + + +protected: + utility::string_t m_Exchange_id; + bool m_Exchange_idIsSet; + std::vector> m_Data; + bool m_DataIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Position_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.cpp new file mode 100644 index 0000000000..d5f612f900 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.cpp @@ -0,0 +1,538 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Position_data.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +Position_data::Position_data() +{ + m_Symbol_id_exchange = utility::conversions::to_string_t(""); + m_Symbol_id_exchangeIsSet = false; + m_Symbol_id_coinapi = utility::conversions::to_string_t(""); + m_Symbol_id_coinapiIsSet = false; + m_Avg_entry_price = 0.0; + m_Avg_entry_priceIsSet = false; + m_Quantity = 0.0; + m_QuantityIsSet = false; + m_SideIsSet = false; + m_Unrealized_pnl = 0.0; + m_Unrealized_pnlIsSet = false; + m_Leverage = 0.0; + m_LeverageIsSet = false; + m_Cross_margin = false; + m_Cross_marginIsSet = false; + m_Liquidation_price = 0.0; + m_Liquidation_priceIsSet = false; + m_Raw_dataIsSet = false; +} + +Position_data::~Position_data() +{ +} + +void Position_data::validate() +{ + // TODO: implement validation +} + +web::json::value Position_data::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_Symbol_id_exchangeIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_exchange"))] = ModelBase::toJson(m_Symbol_id_exchange); + } + if(m_Symbol_id_coinapiIsSet) + { + val[utility::conversions::to_string_t(U("symbol_id_coinapi"))] = ModelBase::toJson(m_Symbol_id_coinapi); + } + if(m_Avg_entry_priceIsSet) + { + val[utility::conversions::to_string_t(U("avg_entry_price"))] = ModelBase::toJson(m_Avg_entry_price); + } + if(m_QuantityIsSet) + { + val[utility::conversions::to_string_t(U("quantity"))] = ModelBase::toJson(m_Quantity); + } + if(m_SideIsSet) + { + val[utility::conversions::to_string_t(U("side"))] = ModelBase::toJson(m_Side); + } + if(m_Unrealized_pnlIsSet) + { + val[utility::conversions::to_string_t(U("unrealized_pnl"))] = ModelBase::toJson(m_Unrealized_pnl); + } + if(m_LeverageIsSet) + { + val[utility::conversions::to_string_t(U("leverage"))] = ModelBase::toJson(m_Leverage); + } + if(m_Cross_marginIsSet) + { + val[utility::conversions::to_string_t(U("cross_margin"))] = ModelBase::toJson(m_Cross_margin); + } + if(m_Liquidation_priceIsSet) + { + val[utility::conversions::to_string_t(U("liquidation_price"))] = ModelBase::toJson(m_Liquidation_price); + } + if(m_Raw_dataIsSet) + { + val[utility::conversions::to_string_t(U("raw_data"))] = ModelBase::toJson(m_Raw_data); + } + + return val; +} + +bool Position_data::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_exchange"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_exchange); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + } + if(val.has_field(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("symbol_id_coinapi"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromJson(fieldValue, refVal_symbol_id_coinapi); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + } + if(val.has_field(utility::conversions::to_string_t(U("avg_entry_price")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("avg_entry_price"))); + if(!fieldValue.is_null()) + { + double refVal_avg_entry_price; + ok &= ModelBase::fromJson(fieldValue, refVal_avg_entry_price); + setAvgEntryPrice(refVal_avg_entry_price); + } + } + if(val.has_field(utility::conversions::to_string_t(U("quantity")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("quantity"))); + if(!fieldValue.is_null()) + { + double refVal_quantity; + ok &= ModelBase::fromJson(fieldValue, refVal_quantity); + setQuantity(refVal_quantity); + } + } + if(val.has_field(utility::conversions::to_string_t(U("side")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("side"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromJson(fieldValue, refVal_side); + setSide(refVal_side); + } + } + if(val.has_field(utility::conversions::to_string_t(U("unrealized_pnl")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("unrealized_pnl"))); + if(!fieldValue.is_null()) + { + double refVal_unrealized_pnl; + ok &= ModelBase::fromJson(fieldValue, refVal_unrealized_pnl); + setUnrealizedPnl(refVal_unrealized_pnl); + } + } + if(val.has_field(utility::conversions::to_string_t(U("leverage")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("leverage"))); + if(!fieldValue.is_null()) + { + double refVal_leverage; + ok &= ModelBase::fromJson(fieldValue, refVal_leverage); + setLeverage(refVal_leverage); + } + } + if(val.has_field(utility::conversions::to_string_t(U("cross_margin")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("cross_margin"))); + if(!fieldValue.is_null()) + { + bool refVal_cross_margin; + ok &= ModelBase::fromJson(fieldValue, refVal_cross_margin); + setCrossMargin(refVal_cross_margin); + } + } + if(val.has_field(utility::conversions::to_string_t(U("liquidation_price")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("liquidation_price"))); + if(!fieldValue.is_null()) + { + double refVal_liquidation_price; + ok &= ModelBase::fromJson(fieldValue, refVal_liquidation_price); + setLiquidationPrice(refVal_liquidation_price); + } + } + if(val.has_field(utility::conversions::to_string_t(U("raw_data")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("raw_data"))); + if(!fieldValue.is_null()) + { + std::shared_ptr refVal_raw_data; + ok &= ModelBase::fromJson(fieldValue, refVal_raw_data); + setRawData(refVal_raw_data); + } + } + return ok; +} + +void Position_data::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_Symbol_id_exchangeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_exchange")), m_Symbol_id_exchange)); + } + if(m_Symbol_id_coinapiIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("symbol_id_coinapi")), m_Symbol_id_coinapi)); + } + if(m_Avg_entry_priceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("avg_entry_price")), m_Avg_entry_price)); + } + if(m_QuantityIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("quantity")), m_Quantity)); + } + if(m_SideIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("side")), m_Side)); + } + if(m_Unrealized_pnlIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("unrealized_pnl")), m_Unrealized_pnl)); + } + if(m_LeverageIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("leverage")), m_Leverage)); + } + if(m_Cross_marginIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("cross_margin")), m_Cross_margin)); + } + if(m_Liquidation_priceIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("liquidation_price")), m_Liquidation_price)); + } + if(m_Raw_dataIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("raw_data")), m_Raw_data)); + } +} + +bool Position_data::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_exchange")))) + { + utility::string_t refVal_symbol_id_exchange; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_exchange"))), refVal_symbol_id_exchange ); + setSymbolIdExchange(refVal_symbol_id_exchange); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("symbol_id_coinapi")))) + { + utility::string_t refVal_symbol_id_coinapi; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("symbol_id_coinapi"))), refVal_symbol_id_coinapi ); + setSymbolIdCoinapi(refVal_symbol_id_coinapi); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("avg_entry_price")))) + { + double refVal_avg_entry_price; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("avg_entry_price"))), refVal_avg_entry_price ); + setAvgEntryPrice(refVal_avg_entry_price); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("quantity")))) + { + double refVal_quantity; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("quantity"))), refVal_quantity ); + setQuantity(refVal_quantity); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("side")))) + { + std::shared_ptr refVal_side; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("side"))), refVal_side ); + setSide(refVal_side); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("unrealized_pnl")))) + { + double refVal_unrealized_pnl; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("unrealized_pnl"))), refVal_unrealized_pnl ); + setUnrealizedPnl(refVal_unrealized_pnl); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("leverage")))) + { + double refVal_leverage; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("leverage"))), refVal_leverage ); + setLeverage(refVal_leverage); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("cross_margin")))) + { + bool refVal_cross_margin; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("cross_margin"))), refVal_cross_margin ); + setCrossMargin(refVal_cross_margin); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("liquidation_price")))) + { + double refVal_liquidation_price; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("liquidation_price"))), refVal_liquidation_price ); + setLiquidationPrice(refVal_liquidation_price); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("raw_data")))) + { + std::shared_ptr refVal_raw_data; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("raw_data"))), refVal_raw_data ); + setRawData(refVal_raw_data); + } + return ok; +} + +utility::string_t Position_data::getSymbolIdExchange() const +{ + return m_Symbol_id_exchange; +} + +void Position_data::setSymbolIdExchange(const utility::string_t& value) +{ + m_Symbol_id_exchange = value; + m_Symbol_id_exchangeIsSet = true; +} + +bool Position_data::symbolIdExchangeIsSet() const +{ + return m_Symbol_id_exchangeIsSet; +} + +void Position_data::unsetSymbol_id_exchange() +{ + m_Symbol_id_exchangeIsSet = false; +} +utility::string_t Position_data::getSymbolIdCoinapi() const +{ + return m_Symbol_id_coinapi; +} + +void Position_data::setSymbolIdCoinapi(const utility::string_t& value) +{ + m_Symbol_id_coinapi = value; + m_Symbol_id_coinapiIsSet = true; +} + +bool Position_data::symbolIdCoinapiIsSet() const +{ + return m_Symbol_id_coinapiIsSet; +} + +void Position_data::unsetSymbol_id_coinapi() +{ + m_Symbol_id_coinapiIsSet = false; +} +double Position_data::getAvgEntryPrice() const +{ + return m_Avg_entry_price; +} + +void Position_data::setAvgEntryPrice(double value) +{ + m_Avg_entry_price = value; + m_Avg_entry_priceIsSet = true; +} + +bool Position_data::avgEntryPriceIsSet() const +{ + return m_Avg_entry_priceIsSet; +} + +void Position_data::unsetAvg_entry_price() +{ + m_Avg_entry_priceIsSet = false; +} +double Position_data::getQuantity() const +{ + return m_Quantity; +} + +void Position_data::setQuantity(double value) +{ + m_Quantity = value; + m_QuantityIsSet = true; +} + +bool Position_data::quantityIsSet() const +{ + return m_QuantityIsSet; +} + +void Position_data::unsetQuantity() +{ + m_QuantityIsSet = false; +} +std::shared_ptr Position_data::getSide() const +{ + return m_Side; +} + +void Position_data::setSide(const std::shared_ptr& value) +{ + m_Side = value; + m_SideIsSet = true; +} + +bool Position_data::sideIsSet() const +{ + return m_SideIsSet; +} + +void Position_data::unsetSide() +{ + m_SideIsSet = false; +} +double Position_data::getUnrealizedPnl() const +{ + return m_Unrealized_pnl; +} + +void Position_data::setUnrealizedPnl(double value) +{ + m_Unrealized_pnl = value; + m_Unrealized_pnlIsSet = true; +} + +bool Position_data::unrealizedPnlIsSet() const +{ + return m_Unrealized_pnlIsSet; +} + +void Position_data::unsetUnrealized_pnl() +{ + m_Unrealized_pnlIsSet = false; +} +double Position_data::getLeverage() const +{ + return m_Leverage; +} + +void Position_data::setLeverage(double value) +{ + m_Leverage = value; + m_LeverageIsSet = true; +} + +bool Position_data::leverageIsSet() const +{ + return m_LeverageIsSet; +} + +void Position_data::unsetLeverage() +{ + m_LeverageIsSet = false; +} +bool Position_data::isCrossMargin() const +{ + return m_Cross_margin; +} + +void Position_data::setCrossMargin(bool value) +{ + m_Cross_margin = value; + m_Cross_marginIsSet = true; +} + +bool Position_data::crossMarginIsSet() const +{ + return m_Cross_marginIsSet; +} + +void Position_data::unsetCross_margin() +{ + m_Cross_marginIsSet = false; +} +double Position_data::getLiquidationPrice() const +{ + return m_Liquidation_price; +} + +void Position_data::setLiquidationPrice(double value) +{ + m_Liquidation_price = value; + m_Liquidation_priceIsSet = true; +} + +bool Position_data::liquidationPriceIsSet() const +{ + return m_Liquidation_priceIsSet; +} + +void Position_data::unsetLiquidation_price() +{ + m_Liquidation_priceIsSet = false; +} +std::shared_ptr Position_data::getRawData() const +{ + return m_Raw_data; +} + +void Position_data::setRawData(const std::shared_ptr& value) +{ + m_Raw_data = value; + m_Raw_dataIsSet = true; +} + +bool Position_data::rawDataIsSet() const +{ + return m_Raw_dataIsSet; +} + +void Position_data::unsetRaw_data() +{ + m_Raw_dataIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.h new file mode 100644 index 0000000000..1d774db378 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/Position_data.h @@ -0,0 +1,179 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Position_data.h + * + * The Position object. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Position_data_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_Position_data_H_ + + +#include "ModelBase.h" + +#include "model/OrdSide.h" +#include +#include "Object.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// The Position object. +/// +class Position_data + : public ModelBase +{ +public: + Position_data(); + virtual ~Position_data(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// Position_data members + + /// + /// Exchange symbol. + /// + utility::string_t getSymbolIdExchange() const; + bool symbolIdExchangeIsSet() const; + void unsetSymbol_id_exchange(); + + void setSymbolIdExchange(const utility::string_t& value); + + /// + /// CoinAPI symbol. + /// + utility::string_t getSymbolIdCoinapi() const; + bool symbolIdCoinapiIsSet() const; + void unsetSymbol_id_coinapi(); + + void setSymbolIdCoinapi(const utility::string_t& value); + + /// + /// Calculated average price of all fills on this position. + /// + double getAvgEntryPrice() const; + bool avgEntryPriceIsSet() const; + void unsetAvg_entry_price(); + + void setAvgEntryPrice(double value); + + /// + /// The current position quantity. + /// + double getQuantity() const; + bool quantityIsSet() const; + void unsetQuantity(); + + void setQuantity(double value); + + /// + /// + /// + std::shared_ptr getSide() const; + bool sideIsSet() const; + void unsetSide(); + + void setSide(const std::shared_ptr& value); + + /// + /// Unrealised profit or loss (PNL) of this position. + /// + double getUnrealizedPnl() const; + bool unrealizedPnlIsSet() const; + void unsetUnrealized_pnl(); + + void setUnrealizedPnl(double value); + + /// + /// Leverage for this position reported by the exchange. + /// + double getLeverage() const; + bool leverageIsSet() const; + void unsetLeverage(); + + void setLeverage(double value); + + /// + /// Is cross margin mode enable for this position? + /// + bool isCrossMargin() const; + bool crossMarginIsSet() const; + void unsetCross_margin(); + + void setCrossMargin(bool value); + + /// + /// Liquidation price. If mark price will reach this value, the position will be liquidated. + /// + double getLiquidationPrice() const; + bool liquidationPriceIsSet() const; + void unsetLiquidation_price(); + + void setLiquidationPrice(double value); + + /// + /// + /// + std::shared_ptr getRawData() const; + bool rawDataIsSet() const; + void unsetRaw_data(); + + void setRawData(const std::shared_ptr& value); + + +protected: + utility::string_t m_Symbol_id_exchange; + bool m_Symbol_id_exchangeIsSet; + utility::string_t m_Symbol_id_coinapi; + bool m_Symbol_id_coinapiIsSet; + double m_Avg_entry_price; + bool m_Avg_entry_priceIsSet; + double m_Quantity; + bool m_QuantityIsSet; + std::shared_ptr m_Side; + bool m_SideIsSet; + double m_Unrealized_pnl; + bool m_Unrealized_pnlIsSet; + double m_Leverage; + bool m_LeverageIsSet; + bool m_Cross_margin; + bool m_Cross_marginIsSet; + double m_Liquidation_price; + bool m_Liquidation_priceIsSet; + std::shared_ptr m_Raw_data; + bool m_Raw_dataIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Position_data_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.cpp new file mode 100644 index 0000000000..a5db1c4190 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.cpp @@ -0,0 +1,145 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "RejectReason.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +namespace +{ +using EnumUnderlyingType = utility::string_t; + +RejectReason::eRejectReason toEnum(const EnumUnderlyingType& val) +{ + if (val == utility::conversions::to_string_t(U("OTHER"))) + return RejectReason::eRejectReason::RejectReason_OTHER; + if (val == utility::conversions::to_string_t(U("EXCHANGE_UNREACHABLE"))) + return RejectReason::eRejectReason::RejectReason_EXCHANGE_UNREACHABLE; + if (val == utility::conversions::to_string_t(U("EXCHANGE_RESPONSE_TIMEOUT"))) + return RejectReason::eRejectReason::RejectReason_EXCHANGE_RESPONSE_TIMEOUT; + if (val == utility::conversions::to_string_t(U("ORDER_ID_NOT_FOUND"))) + return RejectReason::eRejectReason::RejectReason_ORDER_ID_NOT_FOUND; + if (val == utility::conversions::to_string_t(U("INVALID_TYPE"))) + return RejectReason::eRejectReason::RejectReason_INVALID_TYPE; + if (val == utility::conversions::to_string_t(U("METHOD_NOT_SUPPORTED"))) + return RejectReason::eRejectReason::RejectReason_METHOD_NOT_SUPPORTED; + if (val == utility::conversions::to_string_t(U("JSON_ERROR"))) + return RejectReason::eRejectReason::RejectReason_JSON_ERROR; + return {}; +} + +EnumUnderlyingType fromEnum(RejectReason::eRejectReason e) +{ + switch (e) + { + case RejectReason::eRejectReason::RejectReason_OTHER: + return U("OTHER"); + case RejectReason::eRejectReason::RejectReason_EXCHANGE_UNREACHABLE: + return U("EXCHANGE_UNREACHABLE"); + case RejectReason::eRejectReason::RejectReason_EXCHANGE_RESPONSE_TIMEOUT: + return U("EXCHANGE_RESPONSE_TIMEOUT"); + case RejectReason::eRejectReason::RejectReason_ORDER_ID_NOT_FOUND: + return U("ORDER_ID_NOT_FOUND"); + case RejectReason::eRejectReason::RejectReason_INVALID_TYPE: + return U("INVALID_TYPE"); + case RejectReason::eRejectReason::RejectReason_METHOD_NOT_SUPPORTED: + return U("METHOD_NOT_SUPPORTED"); + case RejectReason::eRejectReason::RejectReason_JSON_ERROR: + return U("JSON_ERROR"); + default: + break; + } + return {}; +} +} + +RejectReason::RejectReason() +{ +} + +RejectReason::~RejectReason() +{ +} + +void RejectReason::validate() +{ + // TODO: implement validation +} + +web::json::value RejectReason::toJson() const +{ + auto val = fromEnum(m_value); + return web::json::value(val); +} + +bool RejectReason::fromJson(const web::json::value& val) +{ + m_value = toEnum(val.as_string()); + return true; +} + +void RejectReason::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + + auto e = fromEnum(m_value); + multipart->add(ModelBase::toHttpContent(namePrefix, e)); +} + +bool RejectReason::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + { + EnumUnderlyingType e; + ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e); + if (ok) + { + auto v = toEnum(e); + setValue(v); + } + } + return ok; +} + +RejectReason::eRejectReason RejectReason::getValue() const +{ + return m_value; +} + +void RejectReason::setValue(RejectReason::eRejectReason const value) +{ + m_value = value; +} + + +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.h new file mode 100644 index 0000000000..31017cbae9 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/RejectReason.h @@ -0,0 +1,72 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * RejectReason.h + * + * Cause of rejection. + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_RejectReason_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_RejectReason_H_ + + +#include "ModelBase.h" + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class RejectReason + : public ModelBase +{ +public: + RejectReason(); + virtual ~RejectReason(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + enum class eRejectReason + { + RejectReason_OTHER, + RejectReason_EXCHANGE_UNREACHABLE, + RejectReason_EXCHANGE_RESPONSE_TIMEOUT, + RejectReason_ORDER_ID_NOT_FOUND, + RejectReason_INVALID_TYPE, + RejectReason_METHOD_NOT_SUPPORTED, + RejectReason_JSON_ERROR, + }; + + eRejectReason getValue() const; + void setValue(eRejectReason const value); + + protected: + eRejectReason m_value; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_RejectReason_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.cpp new file mode 100644 index 0000000000..c3f7031ac1 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.cpp @@ -0,0 +1,137 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "TimeInForce.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + +namespace +{ +using EnumUnderlyingType = utility::string_t; + +TimeInForce::eTimeInForce toEnum(const EnumUnderlyingType& val) +{ + if (val == utility::conversions::to_string_t(U("GOOD_TILL_CANCEL"))) + return TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_CANCEL; + if (val == utility::conversions::to_string_t(U("GOOD_TILL_TIME_EXCHANGE"))) + return TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_TIME_EXCHANGE; + if (val == utility::conversions::to_string_t(U("GOOD_TILL_TIME_OMS"))) + return TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_TIME_OMS; + if (val == utility::conversions::to_string_t(U("FILL_OR_KILL"))) + return TimeInForce::eTimeInForce::TimeInForce_FILL_OR_KILL; + if (val == utility::conversions::to_string_t(U("IMMEDIATE_OR_CANCEL"))) + return TimeInForce::eTimeInForce::TimeInForce_IMMEDIATE_OR_CANCEL; + return {}; +} + +EnumUnderlyingType fromEnum(TimeInForce::eTimeInForce e) +{ + switch (e) + { + case TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_CANCEL: + return U("GOOD_TILL_CANCEL"); + case TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_TIME_EXCHANGE: + return U("GOOD_TILL_TIME_EXCHANGE"); + case TimeInForce::eTimeInForce::TimeInForce_GOOD_TILL_TIME_OMS: + return U("GOOD_TILL_TIME_OMS"); + case TimeInForce::eTimeInForce::TimeInForce_FILL_OR_KILL: + return U("FILL_OR_KILL"); + case TimeInForce::eTimeInForce::TimeInForce_IMMEDIATE_OR_CANCEL: + return U("IMMEDIATE_OR_CANCEL"); + default: + break; + } + return {}; +} +} + +TimeInForce::TimeInForce() +{ +} + +TimeInForce::~TimeInForce() +{ +} + +void TimeInForce::validate() +{ + // TODO: implement validation +} + +web::json::value TimeInForce::toJson() const +{ + auto val = fromEnum(m_value); + return web::json::value(val); +} + +bool TimeInForce::fromJson(const web::json::value& val) +{ + m_value = toEnum(val.as_string()); + return true; +} + +void TimeInForce::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + + auto e = fromEnum(m_value); + multipart->add(ModelBase::toHttpContent(namePrefix, e)); +} + +bool TimeInForce::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if (!namePrefix.empty() && namePrefix.back() != U('.')) + { + namePrefix.push_back(U('.')); + } + { + EnumUnderlyingType e; + ok = ModelBase::fromHttpContent(multipart->getContent(namePrefix), e); + if (ok) + { + auto v = toEnum(e); + setValue(v); + } + } + return ok; +} + +TimeInForce::eTimeInForce TimeInForce::getValue() const +{ + return m_value; +} + +void TimeInForce::setValue(TimeInForce::eTimeInForce const value) +{ + m_value = value; +} + + +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.h new file mode 100644 index 0000000000..97412a0065 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/TimeInForce.h @@ -0,0 +1,70 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * TimeInForce.h + * + * Order time in force options are documented in the separate section: <a href=\"#ems-order-params-tif\">EMS / Starter Guide / Order parameters / Time in force</a> + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_TimeInForce_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_TimeInForce_H_ + + +#include "ModelBase.h" + + +namespace org { +namespace openapitools { +namespace client { +namespace model { + +class TimeInForce + : public ModelBase +{ +public: + TimeInForce(); + virtual ~TimeInForce(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + enum class eTimeInForce + { + TimeInForce_GOOD_TILL_CANCEL, + TimeInForce_GOOD_TILL_TIME_EXCHANGE, + TimeInForce_GOOD_TILL_TIME_OMS, + TimeInForce_FILL_OR_KILL, + TimeInForce_IMMEDIATE_OR_CANCEL, + }; + + eTimeInForce getValue() const; + void setValue(eTimeInForce const value); + + protected: + eTimeInForce m_value; +}; + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_TimeInForce_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.cpp b/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.cpp new file mode 100644 index 0000000000..30cdf36ab7 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.cpp @@ -0,0 +1,310 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ValidationError.h" + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + + + +ValidationError::ValidationError() +{ + m_Type = utility::conversions::to_string_t(""); + m_TypeIsSet = false; + m_Title = utility::conversions::to_string_t(""); + m_TitleIsSet = false; + m_Status = 0.0; + m_StatusIsSet = false; + m_TraceId = utility::conversions::to_string_t(""); + m_TraceIdIsSet = false; + m_Errors = utility::conversions::to_string_t(""); + m_ErrorsIsSet = false; +} + +ValidationError::~ValidationError() +{ +} + +void ValidationError::validate() +{ + // TODO: implement validation +} + +web::json::value ValidationError::toJson() const +{ + + web::json::value val = web::json::value::object(); + + if(m_TypeIsSet) + { + val[utility::conversions::to_string_t(U("type"))] = ModelBase::toJson(m_Type); + } + if(m_TitleIsSet) + { + val[utility::conversions::to_string_t(U("title"))] = ModelBase::toJson(m_Title); + } + if(m_StatusIsSet) + { + val[utility::conversions::to_string_t(U("status"))] = ModelBase::toJson(m_Status); + } + if(m_TraceIdIsSet) + { + val[utility::conversions::to_string_t(U("traceId"))] = ModelBase::toJson(m_TraceId); + } + if(m_ErrorsIsSet) + { + val[utility::conversions::to_string_t(U("errors"))] = ModelBase::toJson(m_Errors); + } + + return val; +} + +bool ValidationError::fromJson(const web::json::value& val) +{ + bool ok = true; + + if(val.has_field(utility::conversions::to_string_t(U("type")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("type"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_type; + ok &= ModelBase::fromJson(fieldValue, refVal_type); + setType(refVal_type); + } + } + if(val.has_field(utility::conversions::to_string_t(U("title")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("title"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_title; + ok &= ModelBase::fromJson(fieldValue, refVal_title); + setTitle(refVal_title); + } + } + if(val.has_field(utility::conversions::to_string_t(U("status")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("status"))); + if(!fieldValue.is_null()) + { + double refVal_status; + ok &= ModelBase::fromJson(fieldValue, refVal_status); + setStatus(refVal_status); + } + } + if(val.has_field(utility::conversions::to_string_t(U("traceId")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("traceId"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_traceId; + ok &= ModelBase::fromJson(fieldValue, refVal_traceId); + setTraceId(refVal_traceId); + } + } + if(val.has_field(utility::conversions::to_string_t(U("errors")))) + { + const web::json::value& fieldValue = val.at(utility::conversions::to_string_t(U("errors"))); + if(!fieldValue.is_null()) + { + utility::string_t refVal_errors; + ok &= ModelBase::fromJson(fieldValue, refVal_errors); + setErrors(refVal_errors); + } + } + return ok; +} + +void ValidationError::toMultipart(std::shared_ptr multipart, const utility::string_t& prefix) const +{ + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + if(m_TypeIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("type")), m_Type)); + } + if(m_TitleIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("title")), m_Title)); + } + if(m_StatusIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("status")), m_Status)); + } + if(m_TraceIdIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("traceId")), m_TraceId)); + } + if(m_ErrorsIsSet) + { + multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t(U("errors")), m_Errors)); + } +} + +bool ValidationError::fromMultiPart(std::shared_ptr multipart, const utility::string_t& prefix) +{ + bool ok = true; + utility::string_t namePrefix = prefix; + if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(U("."))) + { + namePrefix += utility::conversions::to_string_t(U(".")); + } + + if(multipart->hasContent(utility::conversions::to_string_t(U("type")))) + { + utility::string_t refVal_type; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("type"))), refVal_type ); + setType(refVal_type); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("title")))) + { + utility::string_t refVal_title; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("title"))), refVal_title ); + setTitle(refVal_title); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("status")))) + { + double refVal_status; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("status"))), refVal_status ); + setStatus(refVal_status); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("traceId")))) + { + utility::string_t refVal_traceId; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("traceId"))), refVal_traceId ); + setTraceId(refVal_traceId); + } + if(multipart->hasContent(utility::conversions::to_string_t(U("errors")))) + { + utility::string_t refVal_errors; + ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t(U("errors"))), refVal_errors ); + setErrors(refVal_errors); + } + return ok; +} + +utility::string_t ValidationError::getType() const +{ + return m_Type; +} + +void ValidationError::setType(const utility::string_t& value) +{ + m_Type = value; + m_TypeIsSet = true; +} + +bool ValidationError::typeIsSet() const +{ + return m_TypeIsSet; +} + +void ValidationError::unsetType() +{ + m_TypeIsSet = false; +} +utility::string_t ValidationError::getTitle() const +{ + return m_Title; +} + +void ValidationError::setTitle(const utility::string_t& value) +{ + m_Title = value; + m_TitleIsSet = true; +} + +bool ValidationError::titleIsSet() const +{ + return m_TitleIsSet; +} + +void ValidationError::unsetTitle() +{ + m_TitleIsSet = false; +} +double ValidationError::getStatus() const +{ + return m_Status; +} + +void ValidationError::setStatus(double value) +{ + m_Status = value; + m_StatusIsSet = true; +} + +bool ValidationError::statusIsSet() const +{ + return m_StatusIsSet; +} + +void ValidationError::unsetStatus() +{ + m_StatusIsSet = false; +} +utility::string_t ValidationError::getTraceId() const +{ + return m_TraceId; +} + +void ValidationError::setTraceId(const utility::string_t& value) +{ + m_TraceId = value; + m_TraceIdIsSet = true; +} + +bool ValidationError::traceIdIsSet() const +{ + return m_TraceIdIsSet; +} + +void ValidationError::unsetTraceId() +{ + m_TraceIdIsSet = false; +} +utility::string_t ValidationError::getErrors() const +{ + return m_Errors; +} + +void ValidationError::setErrors(const utility::string_t& value) +{ + m_Errors = value; + m_ErrorsIsSet = true; +} + +bool ValidationError::errorsIsSet() const +{ + return m_ErrorsIsSet; +} + +void ValidationError::unsetErrors() +{ + m_ErrorsIsSet = false; +} +} +} +} +} + + diff --git a/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.h b/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.h new file mode 100644 index 0000000000..048b6a4d3d --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-restsdk/model/ValidationError.h @@ -0,0 +1,122 @@ +/** + * EMS - REST API + * This section will provide necessary information about the `CoinAPI EMS REST API` protocol.
This API is also available in the Postman application: https://postman.coinapi.io/

Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) ### Endpoints
Deployment method Environment Url
Managed Cloud Production Use Managed Cloud REST API /v1/locations to get specific endpoints to each server site where your deployments span
Managed Cloud Sandbox https://ems-gateway-aws-eu-central-1-dev.coinapi.io/
Self Hosted Production IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
Self Hosted Sandbox IP Address of the ems-gateway container/excecutable in the closest server site to the caller location
### Authentication If the software is deployed as `Self-Hosted` then API do not require authentication as inside your infrastructure, your company is responsible for the security and access controls.

If the software is deployed in our `Managed Cloud`, there are 2 methods for authenticating with us, you only need to use one: 1. Custom authorization header named `X-CoinAPI-Key` with the API Key 2. Query string parameter named `apikey` with the API Key 3. TLS Client Certificate from the `Managed Cloud REST API` (/v1/certificate/pem endpoint) while establishing a TLS session with us. #### Custom authorization header You can authorize by providing additional custom header named `X-CoinAPI-Key` and API key as its value. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY`, then the authorization header you should send to us will look like:

`X-CoinAPI-Key: 73034021-THIS-IS-SAMPLE-KEY` #### Query string authorization parameter You can authorize by providing an additional parameter named `apikey` with a value equal to your API key in the query string of your HTTP request. Assuming that your API key is `73034021-THIS-IS-SAMPLE-KEY` and that you want to request all balances, then your query string should look like this:

`GET /v1/balances?apikey=73034021-THIS-IS-SAMPLE-KEY` + * + * The version of the OpenAPI document: v1 + * Contact: support@coinapi.io + * + * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ValidationError.h + * + * + */ + +#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ValidationError_H_ +#define ORG_OPENAPITOOLS_CLIENT_MODEL_ValidationError_H_ + + +#include "ModelBase.h" + +#include + +namespace org { +namespace openapitools { +namespace client { +namespace model { + + +/// +/// +/// +class ValidationError + : public ModelBase +{ +public: + ValidationError(); + virtual ~ValidationError(); + + ///////////////////////////////////////////// + /// ModelBase overrides + + void validate() override; + + web::json::value toJson() const override; + bool fromJson(const web::json::value& json) override; + + void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; + bool fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; + + ///////////////////////////////////////////// + /// ValidationError members + + /// + /// + /// + utility::string_t getType() const; + bool typeIsSet() const; + void unsetType(); + + void setType(const utility::string_t& value); + + /// + /// + /// + utility::string_t getTitle() const; + bool titleIsSet() const; + void unsetTitle(); + + void setTitle(const utility::string_t& value); + + /// + /// + /// + double getStatus() const; + bool statusIsSet() const; + void unsetStatus(); + + void setStatus(double value); + + /// + /// + /// + utility::string_t getTraceId() const; + bool traceIdIsSet() const; + void unsetTraceId(); + + void setTraceId(const utility::string_t& value); + + /// + /// + /// + utility::string_t getErrors() const; + bool errorsIsSet() const; + void unsetErrors(); + + void setErrors(const utility::string_t& value); + + +protected: + utility::string_t m_Type; + bool m_TypeIsSet; + utility::string_t m_Title; + bool m_TitleIsSet; + double m_Status; + bool m_StatusIsSet; + utility::string_t m_TraceId; + bool m_TraceIdIsSet; + utility::string_t m_Errors; + bool m_ErrorsIsSet; +}; + + +} +} +} +} + +#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ValidationError_H_ */ diff --git a/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator-ignore b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/FILES b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/FILES new file mode 100644 index 0000000000..8fffb01925 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/FILES @@ -0,0 +1,52 @@ +.openapi-generator-ignore +doc/Doxyfile +doc/README.md +doc/generateDocumentation.sh +src/Balance.cpp +src/Balance.h +src/BalanceData.cpp +src/BalanceData.h +src/BalancesManager.cpp +src/BalancesManager.h +src/Error.cpp +src/Error.h +src/Fills.cpp +src/Fills.h +src/Helpers.cpp +src/Helpers.h +src/MessageReject.cpp +src/MessageReject.h +src/NetClient.cpp +src/NetClient.h +src/Object.h +src/OrdSide.cpp +src/OrdSide.h +src/OrdStatus.cpp +src/OrdStatus.h +src/OrdType.cpp +src/OrdType.h +src/OrderCancelAllRequest.cpp +src/OrderCancelAllRequest.h +src/OrderCancelSingleRequest.cpp +src/OrderCancelSingleRequest.h +src/OrderExecutionReport.cpp +src/OrderExecutionReport.h +src/OrderExecutionReportAllOf.cpp +src/OrderExecutionReportAllOf.h +src/OrderNewSingleRequest.cpp +src/OrderNewSingleRequest.h +src/OrdersManager.cpp +src/OrdersManager.h +src/Position.cpp +src/Position.h +src/PositionData.cpp +src/PositionData.h +src/PositionsManager.cpp +src/PositionsManager.h +src/RejectReason.cpp +src/RejectReason.h +src/RequestInfo.h +src/TimeInForce.cpp +src/TimeInForce.h +src/ValidationError.cpp +src/ValidationError.h diff --git a/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/VERSION b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/VERSION new file mode 100644 index 0000000000..1e20ec35c6 --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-tizen/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0 \ No newline at end of file diff --git a/ems-cloud-mgmt-sdk/cpp-tizen/doc/Doxyfile b/ems-cloud-mgmt-sdk/cpp-tizen/doc/Doxyfile new file mode 100644 index 0000000000..ed876bcfab --- /dev/null +++ b/ems-cloud-mgmt-sdk/cpp-tizen/doc/Doxyfile @@ -0,0 +1,2313 @@ +# Doxyfile 1.8.6 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all text +# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv +# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv +# for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "EMS - REST API v1 Tizen SDK" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = v1 + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = "An SDK for creating client applications for EMS - REST API on Tizen Platform (http://tizen.org/)" + +# With the PROJECT_LOGO tag one can specify a logo or icon that is included in +# the documentation. The maximum height of the logo should not exceed 55 pixels +# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo +# to the output directory. + +PROJECT_LOGO = "./doc/logo.png" + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = "./doc/SDK" + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = NO + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a +# new page for each member. If set to NO, the documentation of a member will be +# part of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make +# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C +# (default is Fortran), use: inc=Fortran f=C. +# +# Note For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by by putting a % sign in front of the word +# or globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = YES + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = NO + +# This flag is only useful for Objective-C code. When set to YES local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO these classes will be included in the various overviews. This option has +# no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = YES + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the +# todo list. This list is created by putting \todo commands in the +# documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the +# test list. This list is created by putting \test commands in the +# documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES the list +# will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. Do not use file names with spaces, bibtex cannot handle them. See +# also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO doxygen will only warn about wrong or incomplete parameter +# documentation, but not about the absence of documentation. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. +# Note: If this tag is empty the current directory is searched. + +INPUT = ./src ./include + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: http://www.gnu.org/software/libiconv) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank the +# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, +# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, +# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, +# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, +# *.qsf, *.as and *.js. + +FILE_PATTERNS = *.h *.cpp + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER ) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# function all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES, then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see http://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the config file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user- +# defined cascading style sheet that is included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefor more robust against future updates. +# Doxygen will copy the style sheet file to the output directory. For an example +# see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the stylesheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# http://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to NO can help when comparing the output of multiple runs. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = YES + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: http://developer.apple.com/tools/xcode/), introduced with +# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler ( hhc.exe). If non-empty +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated ( +# YES) or that it should be included in the master .chm file ( NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated ( +# YES) or a normal table of contents ( NO) in the .chm file. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = YES + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# http://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using prerendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from http://www.mathjax.org before deployment. +# The default value is: http://cdn.mathjax.org/mathjax/latest. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /