Initial commit

This commit is contained in:
Yaser
2026-08-13 19:50:53 +03:30
commit 38084458fe
879 changed files with 95198 additions and 0 deletions

40
docs/airdrop.md Normal file
View File

@@ -0,0 +1,40 @@
# Peatio Airdrop API
This doc describes how you can process airdrops for users using Admin API
### Example for airdrop processing
1. Admin user make an deposit for the total amount of the airdrop on his deposit address for airdrop currency
Also you can do an adjustment for admin account but after airdrop make sure to deposit total amount of the airdrop to the platform hot wallet.
2. Prepare csv file for airdrop with the following format
| uid | currency_id | amount |
|---------------|-------------|--------|
| ID1000003838 | usdt | 100 |
| ID1000003839 | usdt | 100 |
| ID1000003840 | usdt | 100 |
3. Load csv file from Tower in Promo -> Airdrops tab and click Submit button.
Also you can use directly Admin API with POST request to `api/v2/peatio/admin/airdrops`
Example with curl:
```bash
curl -X POST -F 'file=@spec/resources/airdrops/airdrop.csv' 'https://opendax.cloud/api/v2/admin/airdrops'
```
### Rules and exceptions
1. Admin who received deposit for the airdrop total amount shouldV process airdrop from HIS user. Example:
- Admin with uid ID1000001 received 300 usdt on his deposit account.
- Admin with uid ID1000001 login and load csv in airdrop tab.
- Airdrop API will take this user as src account and distribute funds from this account.
2. If user not exist in peatio DB it will be skipped.
3. If currency not exist in peatio DB airdrop will be skipped.
4. If admin doesn't have enough funds for whole airdrop system will not execute any transfers for provided csv.

View File

@@ -0,0 +1,137 @@
# Authenticating in Management API v1
## Step 1: Generate keypair.
`ruby -e "require 'openssl'; require 'base64'; OpenSSL::PKey::RSA.generate(2048).tap { |p| puts '', 'PRIVATE RSA KEY (URL-safe Base64 encoded, PEM):', '', Base64.urlsafe_encode64(p.to_pem), '', 'PUBLIC RSA KEY (URL-safe Base64 encoded, PEM):', '', Base64.urlsafe_encode64(p.public_key.to_pem) }"`
## Step 2: Include public key in the `config/management_api_v1.yml` at Peatio.
You should give the ID to the key and put it in variable called `keychain`.
The variable `keychain` in `config/management_api_v1.yml` should look like:
```yml
keychain:
backend-1.mycompany.example:
algorithm: RS256
value: 'BACKEND_1_PUBLIC_KEY_IN_PEM_FORMAT_BASE64_URLSAFE_ENCODED'
backend-2.mycompany.example:
algorithm: RS256
value: 'BACKEND_2_PUBLIC_KEY_IN_PEM_FORMAT_BASE64_URLSAFE_ENCODED'
```
The `value` is public key from URL-safe Base64 encoded PEM from the first step.
The `algorithm` is signature algorithm you prefer.
## Step 3: Configure JWT claims.
You can customize JWT verification options using variable `jwt` in `config/management_api_v1.yml`:
```yml
jwt:
verify_jti: true
verify_aud: true
exp_leeway: 180
```
The documentation is available at [jwt repository](https://github.com/jwt/ruby-jwt#support-for-reserved-claim-names).
## Step 4: Configure security scopes.
The `config/management_api_v1.yml` already includes good docs for this step. You can find it at the bottom near variable `scopes`.
## Step 5: Configure JWT provider and deliver private key.
The JWT provider can use Ruby Gem `jwt-multisig` for generating JWT with multiple signatures.
You should store private keys (ID, value, algorithm) somewhere in your application.
To generate JWS use the `JWT::Multisig.generate_jwt(payload, private_keychain, algorithms)`.
In `private_keychain` you need to put private key from URL-safe Base64 encoded PEM from the first step.
The output from this example with serialized JWT will be save in data.json.
Example:
```ruby
require 'openssl'
require 'jwt-multisig'
require 'base64'
require 'json'
payload = {
exp: 1922830281, # Put here all the JWT claims.
data: { foo: 'bar', baz: 'qux' } # Put here all the data your API action expects.
}
# You can choose what signatures the JWT should include.
private_keychain = {
:'backend-1.mycompany.example' => OpenSSL::PKey.read(Base64.urlsafe_decode64('BACKEND_1_PRIVATE_KEY_IN_PEM_FORMAT_BASE64_URLSAFE_ENCODED')),
:'backend-2.mycompany.example' => OpenSSL::PKey.read(Base64.urlsafe_decode64('BACKEND_2_PRIVATE_KEY_IN_PEM_FORMAT_BASE64_URLSAFE_ENCODED'))
}
algorithms = {
:'backend-1.mycompany.example' => 'RS256',
:'backend-2.mycompany.example' => 'RS256'
}
jwt = JWT::Multisig.generate_jwt(payload, private_keychain, algorithms)
Kernel.puts JSON.dump(jwt) # The output will include serialized JWT.
# Save your JWT in data.json
File.open('./data.json','w') do |f|
f.write(jwt.to_json)
end
```
The documentation for this method is available at [rubydoc.info](http://www.rubydoc.info/gems/jwt-multisig/JWT/Multisig#generate_jwt-class_method).
The source code for `jwt-multisig` is available at [GitHub](https://github.com/rubykube/jwt-multisig).
The example JWT is available at [jwt-multisig source code](https://github.com/rubykube/jwt-multisig/blob/master/lib/jwt-multisig.rb#L25).
## Step 6: Make requests to API.
With next example you can make request with ruby Faraday client library or make request with curl. This request will return empty array if you don't have any deposits on the platform.
Example:
```ruby
require 'json'
require 'faraday'
require 'faraday_middleware'
# Read and save your JWT from data.json
data = File.read('./data.json')
# Create HTTP request with ruby Faraday client library
module Faraday
class Connection
alias original_run_request run_request
def run_request(method, url, body, headers, &block)
original_run_request(method, url, body, headers, &block).tap do |response|
response.env.instance_variable_set :@request_body, body if body
end
end
end
end
def http_client
Faraday.new(url: @root_api_url) do |conn|
conn.request :json
conn.response :json
conn.adapter Faraday.default_adapter
end
end
# The output will include request response
Kernel.puts http_client
.public_send(:post,'http://localhost:3000/management_api/v1/deposits', data)
.body
```
Make request with curl.
```
curl -v -H "Accept: application/json" -H "Content-Type: application/json" -d @jwt.json http://localhost:3000/management_api/v1/deposits
```

114
docs/api/errors.md Normal file
View File

@@ -0,0 +1,114 @@
# Peatio Member API Errors
## Shared errors
| Code | Description |
| ----------------------- | ----------------------------------- |
| `jwt.decode_and_verify` | Impossible to decode and verify JWT |
| `record.not_found` | Record Not found |
| `server.internal_error` | Internal Server Error |
## Account module
| Code | Description |
| --------------------------------------- | ---------------------------------------------- |
| `account.currency.doesnt_exist` | **Currency** doesn't exist in database |
| `account.balance.missing_currency` | Parameter **currency** is missing |
| `account.deposit.missing_currency` | Parameter **currency** is missing |
| `account.deposit.invalid_state` | Deposit **state** is not valid |
| `account.deposit.non_integer_limit` | Parameter **limit** should be integer |
| `account.deposit.invalid_limit` | Parameter **limit** is not valid |
| `account.deposit.non_positive_page` | Parameter **page** should be positive number |
| `account.deposit.empty_txid` | Parameter **txid** is empty |
| `account.withdraw.missing_txid` | Parameter **txid** is missing |
| `account.deposit.not_permitted` | Pass the corresponding verification steps to **deposit funds** |
| `account.withdraw.non_integer_limit` | Parameter **limit** should be integer |
| `account.withdraw.invalid_limit` | Parameter **limit** is not valid |
| `account.withdraw.non_positive_page` | Parameter **page** should be positive number |
| `account.withdraw.non_integer_otp` | Parameter **otp** should be integer |
| `account.withdraw.empty_otp` | Parameter **otp** is empty |
| `account.withdraw.missing_otp` | Parameter **otp** is missing |
| `account.withdraw.missing_rid` | Parameter **rid** is missing |
| `account.withdraw.missing_amount` | Parameter **amount** is missing |
| `account.withdraw.missing_currency` | Parameter **currency** is missing |
| `account.withdraw.empty_rid` | Parameter **rid** is empty |
| `account.withdraw.non_decimal_amount` | Parameter **amount** should be decimal |
| `account.withdraw.non_positive_amount` | Parameter **amount** should be positive number |
| `account.withdraw.insufficient_balance` | Account **balance** is insufficient |
| `account.withdraw.invalid_amount` | Parameter **amount** is not valid |
| `account.withdraw.create_error` | Failed to create withdraw |
| `account.withdraw.invalid_otp` | Parameter **otp** is not valid |
| `account.withdraw.disabled_api` | Withdrawal API is disabled |
| `account.withdraw.not_permitted` | Pass the corresponding verification steps to **withdraw funds** |
| `account.withdraw.too_long_note` | Parameter **note** is too long |
| `account.deposit_address.invalid_address_format` | Invalid parameter for deposit address format |
| `account.deposit_address.doesnt_support_cash_address_format` | Currency doesn't support cash address format |
## Market module
| Code | Description |
| -------------------------------------------- | ---------------------------------------------------------------- |
| `market.account.insufficient_balance` | Account balance is insufficient |
| `market.market.doesnt_exist_or_not_enabled` | **Market** doesn't exist in database or currently disabled/hidden|
| `market.order.insufficient_market_liquidity` | Insufficient market liquidity |
| `market.order.invalid_volume_or_price` | Order **volume** or **price** is invalid for selected market |
| `market.order.create_error` | Failed to create order |
| `market.order.cancel_error` | Failed to cancel order |
| `market.order.market_order_price` | Market order doesn't have **price** |
| `market.order.invalid_state` | Parameter **state** is not valid |
| `market.order.invalid_limit` | Parameter **limit** is not valid |
| `market.order.non_integer_limit` | Parameter **limit** should be integer |
| `market.order.invalid_order_by` | Parameter **order_by** is not valid |
| `market.order.invalid_ord_type` | Parameter **ord_type** is not valid |
| `market.order.invalid_type` | Parameter **type** is not valid |
| `market.order.invalid_side` | Parameter **side** is not valid |
| `market.order.missing_market` | Parameter **market** is missing |
| `market.order.missing_side` | Parameter **side** is missing |
| `market.order.missing_volume` | Parameter **volume** is missing |
| `market.order.missing_price` | Parameter **price** is missing |
| `market.order.missing_id` | Parameter **id** is missing |
| `market.order.non_decimal_volume` | Parameter **volume** should be decimal |
| `market.order.non_positive_volume` | Parameter **volume** should be positive number |
| `market.order.invalid_type` | Parameter **type** is not valid |
| `market.order.non_decimal_price` | Parameter **price** should be decimal |
| `market.order.non_positive_price` | Parameter **price** should be positive number |
| `market.order.non_integer_id` | Parameter **id** should be integer |
| `market.order.empty_id` | Parameter **id** is empty |
| `market.trade.non_integer_limit` | Parameter **limit** should be integer |
| `market.trade.invalid_limit` | Parameter **limit** is not valid |
| `market.trade.empty_page` | Parameter **page** is empty |
| `market.trade.non_integer_time_from` | Parameter **time_from** should be integer |
| `market.trade.empty_time_from` | Parameter **time_from** is empty |
| `market.trade.non_integer_time_to` | Parameter **time_to** should be integer |
| `market.trade.empty_time_to_` | Parameter **time_to** is empty |
| `market.trade.invalid_order_by` | Parameter **order_by** is not valid |
| `market.trade.not_permitted` | Pass the corresponding verification steps to **enable trading** |
## Public module
| Code | Description |
| ----------------------------------------- | ---------------------------------------------|
| `public.currency.doesnt_exist` | **Currency** doesn't exist in database |
| `public.currency.invalid_type` | **Currency** type is not valid |
| `public.currency.missing_id` | Parameter **id** is missing |
| `public.market.missing_market` | Parameter **market** is missing |
| `public.market.doesnt_exist` | **Market** doesn't exist in database |
| `public.order_book.non_integer_ask_limit` | Parameter **ask_limit** should be integer |
| `public.order_book.invalid_ask_limit` | Parameter **ask_limit** is not valid |
| `public.order_book.non_integer_bid_limit` | Parameter **bid_limit** should be integer |
| `public.order_book.invalid_bid_limit` | Parameter **bid_limit** is not valid |
| `public.trade.invalid_limit` | Parameter **limit** is not valid |
| `public.trade.non_integer_limit` | Parameter **limit** should be integer |
| `public.trade.non_positive_page` | Parameter **page** should be positive number |
| `public.trade.non_integer_timestamp` | Parameter **timestamp** should be integer |
| `public.trade.invalid_order_by` | Parameter **order_by** is not valid |
| `public.market_depth.non_integer_limit` | Parameter **limit** should be integer |
| `public.market_depth.invalid_limit` | Parameter **limit** is not valid |
| `public.k_line.non_integer_period` | Parameter **period** should be integer |
| `public.k_line.invalid_period` | Parameter **period** is not valid |
| `public.k_line.non_integer_time_from` | Parameter **time_from** should be integer |
| `public.k_line.empty_time_from` | Parameter **time_from** is empty |
| `public.k_line.non_integer_time_to` | Parameter **time_to** should be integer |
| `public.k_line.empty_time_to` | Parameter **time_to** is empty |
| `public.k_line.non_integer_limit` | Parameter **limit** should be integer |
| `public.k_line.invalid_limit` | Parameter **limit** is not valid |

482
docs/api/event_api.md Normal file
View File

@@ -0,0 +1,482 @@
# RabbitMQ Peatio Event API
## Overview of RabbitMQ details
Peatio submits all events into three exchanges depending on event category (read next).
The exchange name consists of three parts:
1) application name, like `peatio`, `barong`.
2) fixed keyword `events`.
3) category of event, like `system` (generic system event), `model` (the attributes of some record were updated), `market` (trading events).
The routing key looks like `deposit.updated`, `btcusd.new_order`.
The event name matches the routing key but with event category appended at the beginning, like `model.deposit.updated`, `market.btcusd.new_order`.
## Overview of RabbitMQ message
Each produced message in `Event API` is JWT (complete format).
This is very similar to `Management API`.
The example below demonstrates both generation and verification of JWT:
```ruby
require "jwt-multisig"
require "securerandom"
jwt_payload = {
iss: "peatio",
jti: SecureRandom.uuid,
iat: Time.now.to_i,
exp: Time.now.to_i + 60,
event: {}
}
require "openssl"
private_key = OpenSSL::PKey::RSA.generate(2048)
public_key = private_key.public_key
generated_jwt = JWT::Multisig.generate_jwt(jwt_payload, { peatio: private_key }, { peatio: "RS256" })
Kernel.puts "GENERATED JWT", generated_jwt.to_json, "\n"
verification_result = JWT::Multisig.verify_jwt generated_jwt.deep_stringify_keys, \
{ peatio: public_key }, { verify_iss: true, iss: "peatio", verify_jti: true }
decoded_jwt_payload = verification_result[:payload]
Kernel.puts "MATCH AFTER VERIFICATION: #{jwt_payload == decoded_jwt_payload}."
```
The RabbitMQ message is stored in JWT field called `event`.
## Overview of Event API message
The typical event looks like (JSON):
```ruby
event: {
name: "model.deposit.updated",
foo: "...",
bar: "...",
qux: "..."
}
```
The field `event[:name]` contains event name (same as routing key).
The fields `foo`, `bar`, `qux` (just for example) are fields which carry useful information.
## Format of `model.deposit.created` event
```ruby
event: {
name: "model.deposit.created",
record: {
tid: "TID9493F6CD41",
user: {
uid: "ID092B2AF8E87",
email: "john@doe.com"
},
uid: "ID092B2AF8E87",
currency: "btc",
amount: "0.0855",
state: "submitted",
created_at: "2018-04-12T17:16:06+03:00",
updated_at: "2018-04-12T17:16:06+03:00",
completed_at: nil,
blockchain_address: "n1Ytj6Hy57YpfueA2vtmnwJQs583bpYn7W",
blockchain_txid: "c37ae1677c4c989dbde9ac22be1f3ff3ac67ed24732a9fa8c9258fdff0232d72",
blockchain_confirmations: 1
}
}
```
| Field | Description |
| ---------- | ----------------------------------- |
| `record` | The up-to-date deposit attributes. |
## Format of `model.deposit.updated` event
```ruby
event: {
name: "model.deposit.updated",
record: {
tid: "TID9493F6CD41",
user: {
uid: "ID092B2AF8E87",
email: "john@doe.com"
},
uid: "ID092B2AF8E87",
currency: "btc",
amount: "0.0855",
state: "accepted",
created_at: "2018-04-12T17:16:06+03:00",
updated_at: "2018-04-12T18:46:57+03:00",
completed_at: "2018-04-12T18:46:57+03:00",
blockchain_address: "n1Ytj6Hy57YpfueA2vtmnwJQs583bpYn7W",
blockchain_txid: "c37ae1677c4c989dbde9ac22be1f3ff3ac67ed24732a9fa8c9258fdff0232d72",
blockchain_confirmations: 7
},
changes: {
state: "submitted",
completed_at: nil,
blockchain_confirmations: 1,
updated_at: "2018-04-12T17:16:06+03:00"
}
}
```
| Field | Description |
| ---------- | ------------------------------------------------ |
| `record` | The up-to-date deposit attributes. |
| `changes` | The changed deposit attributes and their values. |
## Format of `model.withdraw.created` event
```ruby
event: {
name: "model.withdraw.created",
record: {
tid: "TID892F29F094",
user: {
uid: "ID092B2AF8E87",
email: "john@doe.com"
},
uid: "ID092B2AF8E87",
rid: "0xdA35deE8EDDeAA556e4c26268463e26FB91ff74f",
currency: "eth",
amount: "4.5485",
fee: "0.0015",
state: "prepared",
created_at: "2018-04-12T18:52:16+03:00",
updated_at: "2018-04-12T18:52:16+03:00",
completed_at: nil,
blockchain_txid: nil
}
}
```
| Field | Description |
| ---------- | ------------------------------------ |
| `record` | The up-to-date withdraw attributes. |
## Format of `model.withdraw.updated` event
```ruby
event: {
name: "model.withdraw.updated",
record: {
tid: "TID892F29F094",
user: {
uid: "ID092B2AF8E87",
email: "john@doe.com"
},
uid: "ID092B2AF8E87",
rid: "0xdA35deE8EDDeAA556e4c26268463e26FB91ff74f",
currency: "eth",
amount: "4.5485",
fee: "0.0015",
state: "succeed",
created_at: "2018-04-12T18:52:16+03:00",
updated_at: "2018-04-12T18:56:23+03:00",
completed_at: "2018-04-12T18:56:23+03:00",
blockchain_txid: "0x9c34d1750e225a95938f9884e857ab6f55eedda43b159d13abf773fe6a916164"
},
changes: {
state: "processing",
updated_at: "2018-04-12T18:55:39+03:00",
completed_at: "2018-04-12T18:55:39+03:00",
blockchain_txid: nil
}
}
```
| Field | Description |
| ---------- | ------------------------------------------------ |
| `record` | The up-to-date withdraw attributes. |
| `changes` | The changed withdraw attributes and their values. |
## Format of `model.account.created` event
```ruby
event: {
name: "model.account.created",
record: {
id: "1",
member_id: "2",
currency_id: "btc",
balance: "0",
locked: "0",
created_at: "2018-04-12T17:16:06+03:00",
updated_at: "2018-04-12T17:16:06+03:00",
}
}
```
| Field | Description |
| ---------- | ----------------------------------- |
| `record` | The up-to-date account attributes. |
## Format of `model.account.updated` event
```ruby
event: {
name: "model.account.updated",
record: {
id: "1",
member_id: "2",
currency_id: "btc",
balance: "1",
locked: "0",
created_at: "2018-04-12T17:16:06+03:00",
updated_at: "2018-04-12T17:17:06+03:00",
},
changes: {
balance: "0",
updated_at: "2018-04-12T17:16:06+03:00"
}
}
```
| Field | Description |
| ---------- | ------------------------------------------------ |
| `record` | The up-to-date account attributes. |
| `changes` | The changed account attributes and their values. |
## Format of `system.low_hot_wallet_balance` event
```ruby
event: {
name: "system.system.low_hot_wallet_balance",
currency: "btc",
balance: "2.82480099"
}
```
| Field | Description |
| ---------- | ----------------------- |
| `currency` | The currency code. |
| `balance` | The up-to-date balance. |
## Format of `market.btcusd.order_created` event
Buy 14 BTC for 0.42 USD (0.03 USD per BTC).
```ruby
event: {
name: "market.btcusd.order_created",
market: "btcusd",
type: "buy",
trader_uid: "ID022H2NF6E87",
income_unit: "btc",
income_fee_type: "relative",
income_fee_value: "0.0015",
outcome_unit: "usd",
outcome_fee_type: "relative",
outcome_fee_value: "0.0",
initial_income_amount: "14.0",
current_income_amount: "14.0",
initial_outcome_amount: "0.42",
current_outcome_amount: "0.42",
strategy: "limit",
price: "0.03",
state: "open",
trades_count: 0,
created_at: "2018-05-07T02:12:28Z"
}
```
## Format of `market.btcusd.order_updated` event
Sell 100 BTC for 3 USD (0.03 USD per BTC).
```ruby
event: {
name: "market.btcusd.order_updated",
market: "btcusd",
type: "sell",
trader_uid: "ID092B2AF8E87",
income_unit: "usd",
income_fee_type: "relative",
income_fee_value: "0.0015",
outcome_unit: "btc",
outcome_fee_type: "relative",
outcome_fee_value: "0.0",
initial_income_amount: "3.0",
current_income_amount: "2.4",
previous_income_amount: "3.0",
initial_outcome_amount: "100.0",
current_outcome_amount: "80.0",
previous_outcome_amount: "100.0",
strategy: "limit",
price: "0.03",
state: "open",
trades_count: 1,
created_at: "2018-05-07T02:12:28Z",
updated_at: "2018-05-08T10:13:13Z"
}
```
## Format of `market.btcusd.order_canceled` event
Sell 100 BTC for 3 USD (0.03 USD per BTC).
```ruby
event: {
name: "market.btcusd.order_canceled",
market: "btcusd",
type: "sell",
trader_uid: "ID092B2AF8E87",
income_unit: "usd",
income_fee_type: "relative",
income_fee_value: "0.0015",
outcome_unit: "btc",
outcome_fee_type: "relative",
outcome_fee_value: "0.0",
initial_income_amount: "3.0",
current_income_amount: "3.0",
initial_outcome_amount: "100.0",
current_outcome_amount: "100.0",
strategy: "limit",
price: "0.03",
state: "canceled",
trades_count: 0,
created_at: "2018-05-07T02:12:28Z",
canceled_at: "2018-05-08T10:13:13Z"
}
```
## Format of `market.btcusd.order_completed` event
Sell 100 BTC for 3 USD (0.03 USD per BTC).
```ruby
event: {
name: "market.btcusd.order_completed",
market: "btcusd",
type: "sell",
trader_uid: "ID092B2AF8E87",
income_unit: "usd",
income_fee_type: "relative",
income_fee_value: "0.0015",
outcome_unit: "btc",
outcome_fee_type: "relative",
outcome_fee_value: "0.0",
initial_income_amount: "3.0",
current_income_amount: "0.0",
previous_income_amount: "3.0",
initial_outcome_amount: "100.0",
current_outcome_amount: "0.0",
previous_outcome_amount: "100.0",
strategy: "limit",
price: "0.03",
state: "completed",
trades_count: 1,
created_at: "2018-05-07T02:12:28Z",
completed_at: "2018-05-07T17:32:09Z"
}
```
## Format of `market.btcusd.trade_completed` event
```ruby
event: {
name: "market.btcusd.trade_completed",
market: "btcusd",
price: "0.03",
buyer_uid: "ID022H2NF6E87",
buyer_income_unit: "btc",
buyer_income_amount: "14",
buyer_income_fee: "0.021",
buyer_outcome_unit: "usd",
buyer_outcome_amount: "0.42",
buyer_outcome_fee: "0.0",
seller_uid: "ID092B2AF8E87",
seller_income_unit: "usd",
seller_income_amount: "0.42",
seller_income_fee: "0.00063",
seller_outcome_unit: "btc",
seller_outcome_amount: "14.0",
seller_outcome_fee: "0.0",
completed_at: "2018-05-07T17:32:09Z"
}
```
## Producing events using Ruby
```ruby
require "bunny"
def generate_jwt(jwt_payload)
Kernel.abort "Please, see «Overview of RabbitMQ message» for implementation guide."
end
Bunny.run host: "localhost", port: 5672, username: "guest", password: "guest" do |session|
channel = session.channel
exchange = channel.direct("peatio.events.model")
jwt_payload = {
iss: "peatio",
jti: SecureRandom.uuid,
iat: Time.now.to_i,
exp: Time.now.to_i + 60,
event: {
name: "model.deposit.created",
record: {
tid: "TID9493F6CD41",
user: {
uid: "ID092B2AF8E87",
email: "john@doe.com"
},
uid: "ID092B2AF8E87",
currency: "btc",
amount: "0.0855",
state: "submitted",
created_at: "2018-04-12T17:16:06+03:00",
updated_at: "2018-04-12T17:16:06+03:00",
completed_at: nil,
blockchain_address: "n1Ytj6Hy57YpfueA2vtmnwJQs583bpYn7W",
blockchain_txid: "c37ae1677c4c989dbde9ac22be1f3ff3ac67ed24732a9fa8c9258fdff0232d72",
blockchain_confirmations: 1
}
}
}
exchange.publish(generate_jwt(jwt_payload), routing_key: "deposit.created")
end
```
IMPORTANT: Don't forget to implement the logic for JWT exception handling!
## Producing events using `rabbitmqadmin`
`rabbitmqadmin publish routing_key=deposit.created payload=JWT exchange=peatio.events.model`
Don't forget to pass environment variable `JWT`.
## Consuming events using Ruby
```ruby
require "bunny"
def verify_jwt(jwt_payload)
Kernel.abort "Please, see «Overview of RabbitMQ message» for implementation guide."
end
Bunny.run host: "localhost", port: 5672, username: "guest", password: "guest" do |session|
channel = session.channel
exchange = channel.direct("peatio.events.model")
queue = channel.queue("", auto_delete: true, durable: true, exclusive: true)
.bind(exchange, routing_key: "deposit.updated")
queue.subscribe manual_ack: true, block: true do |delivery_info, metadata, payload|
Kernel.puts verify_jwt(JSON.parse(payload)).fetch(:event)
channel.ack(delivery_info.delivery_tag)
rescue => e
channel.nack(delivery_info.delivery_tag, false, true)
end
end
```
IMPORTANT: Don't forget to implement the logic for JWT exception handling!

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

10
docs/api/mask.md Normal file
View File

@@ -0,0 +1,10 @@
# Data masking
Data masking is the process of hiding original data with modified content (characters or other data.)
The main reason for applying masking to a data field is to protect data that is classified as personally identifiable information, sensitive personal data, or commercially sensitive data.
On Peatio beneficiary account number is masked on API level.
| Field | Mask | Comment |
|---|---|---|
| Account number | 42 **** **** 2345 | First 2 number and last 4 digits |

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,943 @@
# Peatio Management API v2
Management API is server-to-server API with high privileges.
## Version: 2.6.0
**Contact information:**
openware.com
<https://www.openware.com>
hello@openware.com
**License:** <https://github.com/openware/peatio/blob/master/LICENSE.md>
### /api/v2/management/peatio/beneficiaries
#### POST
##### Description
Create new beneficiary
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | Beneficiary currency code. | Yes | string |
| name | formData | Human rememberable name which refer beneficiary. | Yes | string |
| description | formData | Human rememberable description which refer beneficiary. | No | string |
| data | formData | Beneficiary data in JSON format | Yes | json |
| uid | formData | The shared user ID. | Yes | string |
| state | formData | Defines either beneficiary active - user can use it to withdraw moneyor pending - requires beneficiary activation with pin. | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Create new beneficiary | [Beneficiary](#beneficiary) |
### /api/v2/management/peatio/beneficiaries/list
#### POST
##### Description
Get list of user beneficiaries
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | Yes | string |
| currency | formData | Beneficiary currency code. | No | string |
| state | formData | Defines either beneficiary active - user can use it to withdraw moneyor pending - requires beneficiary activation with pin. | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Get list of user beneficiaries | [Beneficiary](#beneficiary) |
### /api/v2/management/peatio/accounts/balances
#### POST
##### Description
Queries the non-zero balance accounts for the given currency.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency code. | Yes | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of accounts per page (defaults to 100, maximum is 1000). | No | integer |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Queries the non-zero balance accounts for the given currency. | [Balance](#balance) |
### /api/v2/management/peatio/accounts/balance
#### POST
##### Description
Queries the account balance for the given UID and currency.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | Yes | string |
| currency | formData | The currency code. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Queries the account balance for the given UID and currency. | [Balance](#balance) |
### /api/v2/management/peatio/deposits/state
#### PUT
##### Description
Allows to load money or cancel deposit.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| tid | formData | The shared transaction ID. | Yes | string |
| state | formData | The new state to apply. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Allows to load money or cancel deposit. | [Deposit](#deposit) |
### /api/v2/management/peatio/deposits/new
#### POST
##### Description
Creates new fiat deposit with state set to «submitted». Optionally pass field «state» set to «accepted» if want to load money instantly. You can also use PUT /fiat_deposits/:id later to load money or cancel deposit.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | Yes | string |
| tid | formData | The shared transaction ID. Must not exceed 64 characters. Peatio will generate one automatically unless supplied. | No | string |
| currency | formData | The currency code. | Yes | string |
| amount | formData | The deposit amount. | Yes | double |
| state | formData | The state of deposit. | No | string |
| transfer_type | formData | Deposit transfer type | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new fiat deposit with state set to «submitted». Optionally pass field «state» set to «accepted» if want to load money instantly. You can also use PUT /fiat_deposits/:id later to load money or cancel deposit. | [Deposit](#deposit) |
### /api/v2/management/peatio/deposits/get
#### POST
##### Description
Returns deposit by TID.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| tid | formData | The transaction ID. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns deposit by TID. | [Deposit](#deposit) |
### /api/v2/management/peatio/deposits
#### POST
##### Description
Returns deposits as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | No | string |
| currency | formData | The currency code. | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of deposits per page (defaults to 100, maximum is 1000). | No | integer |
| state | formData | The state to filter by. | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns deposits as paginated collection. | [Deposit](#deposit) |
### /api/v2/management/peatio/withdraws/action
#### PUT
##### Summary
Performs action on withdraw.
##### Description
«process» system will lock the money, check for suspected activity, validate recipient address, and initiate the processing of the withdraw. «cancel» system will mark withdraw as «canceled», and unlock the money.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| tid | formData | The shared transaction ID. | Yes | string |
| action | formData | The action to perform. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Performs action on withdraw. | [Withdraw](#withdraw) |
### /api/v2/management/peatio/withdraws/new
#### POST
##### Summary
Creates new withdraw.
##### Description
Creates new withdraw. The behaviours for fiat and crypto withdraws are different. Fiat: money are immediately locked, withdraw state is set to «submitted», system workers will validate withdraw later against suspected activity, and assign state to «rejected» or «accepted». The processing will not begin automatically. The processing may be initiated manually from admin panel or by PUT /management_api/v1/withdraws/action. Coin: money are immediately locked, withdraw state is set to «submitted», system workers will validate withdraw later against suspected activity, validate withdraw address and set state to «rejected» or «accepted». Then in case state is «accepted» withdraw workers will perform interactions with blockchain. The withdraw receives new state «processing». Then withdraw receives state either «confirming» or «failed».Then in case state is «confirming» withdraw confirmations workers will perform interactions with blockchain.Withdraw receives state «succeed» when it receives minimum necessary amount of confirmations.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | Yes | string |
| tid | formData | The shared transaction ID. Must not exceed 64 characters. Peatio will generate one automatically unless supplied. | No | string |
| rid | formData | The beneficiary ID or wallet address on the Blockchain. | No | string |
| beneficiary_id | formData | ID of Active Beneficiary belonging to user. | No | string |
| currency | formData | The currency code. | Yes | string |
| amount | formData | The amount to withdraw. | Yes | double |
| note | formData | The note for withdraw. | No | string |
| action | formData | The action to perform. | No | string |
| transfer_type | formData | Withdraw transfer type | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new withdraw. | [Withdraw](#withdraw) |
### /api/v2/management/peatio/withdraws/get
#### POST
##### Description
Returns withdraw by ID.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| tid | formData | The shared transaction ID. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns withdraw by ID. | [Withdraw](#withdraw) |
### /api/v2/management/peatio/withdraws
#### POST
##### Description
Returns withdraws as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | No | string |
| currency | formData | The currency code. | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
| state | formData | The state to filter by. | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns withdraws as paginated collection. | [Withdraw](#withdraw) |
### /api/v2/management/peatio/timestamp
#### POST
##### Description
Returns server time in seconds since Unix epoch.
##### Responses
| Code | Description |
| ---- | ----------- |
| 201 | Returns server time in seconds since Unix epoch. |
### /api/v2/management/peatio/assets/new
#### POST
##### Description
Creates new asset operation.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency code. | Yes | string |
| code | formData | Operation account code | Yes | integer |
| debit | formData | Operation debit amount. | No | double |
| credit | formData | Operation credit amount. | No | double |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new asset operation. | [Operation](#operation) |
### /api/v2/management/peatio/assets
#### POST
##### Description
Returns assets as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency for operations filtering. | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
| time_from | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations after the time will be returned. | No | integer |
| time_to | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations before the time will be returned. | No | integer |
| reference_type | formData | The reference type for operations filtering | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns assets as paginated collection. | [Operation](#operation) |
### /api/v2/management/peatio/expenses/new
#### POST
##### Description
Creates new expense operation.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency code. | Yes | string |
| code | formData | Operation account code | Yes | integer |
| debit | formData | Operation debit amount. | No | double |
| credit | formData | Operation credit amount. | No | double |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new expense operation. | [Operation](#operation) |
### /api/v2/management/peatio/expenses
#### POST
##### Description
Returns expenses as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency for operations filtering. | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
| time_from | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations after the time will be returned. | No | integer |
| time_to | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations before the time will be returned. | No | integer |
| reference_type | formData | The reference type for operations filtering | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns expenses as paginated collection. | [Operation](#operation) |
### /api/v2/management/peatio/revenues/new
#### POST
##### Description
Creates new revenue operation.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency code. | Yes | string |
| code | formData | Operation account code | Yes | integer |
| debit | formData | Operation debit amount. | No | double |
| credit | formData | Operation credit amount. | No | double |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new revenue operation. | [Operation](#operation) |
### /api/v2/management/peatio/revenues
#### POST
##### Description
Returns revenues as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency for operations filtering. | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
| time_from | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations after the time will be returned. | No | integer |
| time_to | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations before the time will be returned. | No | integer |
| reference_type | formData | The reference type for operations filtering | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns revenues as paginated collection. | [Operation](#operation) |
### /api/v2/management/peatio/liabilities/new
#### POST
##### Description
Creates new liability operation.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency code. | Yes | string |
| code | formData | Operation account code | Yes | integer |
| uid | formData | The user ID for operation owner. | Yes | string |
| debit | formData | Operation debit amount. | No | double |
| credit | formData | Operation credit amount. | No | double |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Creates new liability operation. | [Operation](#operation) |
### /api/v2/management/peatio/liabilities
#### POST
##### Description
Returns liabilities as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| currency | formData | The currency for operations filtering. | No | string |
| uid | formData | The user ID for operations filtering. | No | string |
| reference_type | formData | The reference type for operations filtering | No | string |
| time_from | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations after the time will be returned. | No | integer |
| time_to | formData | An integer represents the seconds elapsed since Unix epoch.If set, only operations before the time will be returned. | No | integer |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 10000). | No | integer |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns liabilities as paginated collection. | [Operation](#operation) |
### /api/v2/management/peatio/orders/cancel
#### POST
##### Description
Cancel all open orders
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | Filter order by owner uid | No | string |
| market | formData | Unique market id. It's always in the form of xxxyyy,where xxx is the base currency code, yyy is the quotecurrency code, e.g. 'btcusd'. All available markets canbe found at /api/v2/markets. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Cancel all open orders | [Order](#order) |
### /api/v2/management/peatio/orders/{id}/cancel
#### POST
##### Description
Cancel specific order
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| id | path | Unique order id. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Cancel specific order | [Order](#order) |
### /api/v2/management/peatio/orders
#### POST
##### Description
Returns orders
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | Filter order by owner uid | No | string |
| market | formData | Unique market id. It's always in the form of xxxyyy,where xxx is the base currency code, yyy is the quotecurrency code, e.g. 'btcusd'. All available markets canbe found at /api/v2/markets. | No | string |
| state | formData | Filter order by state. | No | string |
| ord_type | formData | Filter order by ord_type. | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns orders | [Order](#order) |
### /api/v2/management/peatio/transfers/new
#### POST
##### Description
Creates new transfer.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| key | formData | Unique Transfer Key. | Yes | string |
| category | formData | Transfer Category. | Yes | string |
| description | formData | Transfer Description. | No | string |
| operations[currency] | formData | Operation currency. | Yes | [ string ] |
| operations[amount] | formData | Operation amount. | Yes | [ double ] |
| operations[account_src][code] | formData | Source Account code. | Yes | [ integer ] |
| operations[account_src][uid] | formData | Source Account User ID (for accounts with member scope). | Yes | [ string ] |
| operations[account_dst][code] | formData | Destination Account code. | Yes | [ integer ] |
| operations[account_dst][uid] | formData | Destination Account User ID (for accounts with member scope). | Yes | [ string ] |
##### Responses
| Code | Description |
| ---- | ----------- |
| 201 | Creates new transfer. |
### /api/v2/management/peatio/trades
#### POST
##### Description
Returns trades as paginated collection.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | No | string |
| market | formData | | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns trades as paginated collection. | [Trade](#trade) |
### /api/v2/management/peatio/members/group
#### POST
##### Description
Set user group.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| uid | formData | The shared user ID. | Yes | string |
| group | formData | User gruop | Yes | string |
##### Responses
| Code | Description |
| ---- | ----------- |
| 201 | Set user group. |
### /api/v2/management/peatio/members
#### POST
##### Description
Create a member.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| email | formData | User email. | Yes | string |
| uid | formData | The shared user ID. | Yes | string |
| level | formData | User level. | Yes | integer |
| role | formData | User role. | Yes | string |
| state | formData | User state. | Yes | string |
| group | formData | User group | Yes | string |
##### Responses
| Code | Description |
| ---- | ----------- |
| 201 | Create a member. |
### /api/v2/management/peatio/fee_schedule/trading_fees
#### POST
##### Description
Returns trading_fees table as paginated collection
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| group | formData | Member group | No | string |
| market_id | formData | Market id | No | string |
| page | formData | The page number (defaults to 1). | No | integer |
| limit | formData | The number of objects per page (defaults to 100, maximum is 1000). | No | integer |
##### Responses
| Code | Description |
| ---- | ----------- |
| 201 | Returns trading_fees table as paginated collection |
### /api/v2/management/peatio/currencies/update
#### PUT
##### Description
Update currency.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| id | formData | Currency code. | Yes | string |
| name | formData | Currency name | No | string |
| deposit_fee | formData | Currency deposit fee | No | double |
| min_deposit_amount | formData | Minimal deposit amount | No | double |
| min_collection_amount | formData | Minimal deposit amount that will be collected | No | double |
| withdraw_fee | formData | Currency withdraw fee | No | double |
| min_withdraw_amount | formData | Minimal withdraw amount | No | double |
| withdraw_limit_24h | formData | Currency 24h withdraw limit | No | double |
| withdraw_limit_72h | formData | Currency 72h withdraw limit | No | double |
| position | formData | Currency position. | No | integer |
| options | formData | Currency options. | No | json |
| visible | formData | Currency display possibility status (true/false). | No | Boolean |
| deposit_enabled | formData | Currency deposit possibility status (true/false). | No | Boolean |
| withdrawal_enabled | formData | Currency withdrawal possibility status (true/false). | No | Boolean |
| precision | formData | Currency precision | No | integer |
| icon_url | formData | Currency icon | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Update currency. | [Currency](#currency) |
### /api/v2/management/peatio/currencies/{code}
#### POST
##### Description
Returns currency by code.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| code | path | The currency code. | Yes | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Returns currency by code. | [Currency](#currency) |
### /api/v2/management/peatio/currencies/list
#### POST
##### Description
Return currencies list.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| type | formData | Currency type | No | string |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Return currencies list. | [Currency](#currency) |
### /api/v2/management/peatio/markets/list
#### POST
##### Description
Return markets list.
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 201 | Return markets list. | [Market](#market) |
### /api/v2/management/peatio/markets/update
#### PUT
##### Description
Update market.
##### Parameters
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ---- |
| id | formData | Unique market id. It's always in the form of xxxyyy,where xxx is the base currency code, yyy is the quotecurrency code, e.g. 'btcusd'. All available markets canbe found at /api/v2/markets. | Yes | string |
| state | formData | Market state defines if user can see/trade on current market. | No | string |
| min_price | formData | Minimum order price. | No | double |
| min_amount | formData | Minimum order amount. | No | double |
| amount_precision | formData | Precision for order amount. | No | integer |
| price_precision | formData | Precision for order price. | No | integer |
| max_price | formData | Maximum order price. | No | double |
| position | formData | Market position. | No | integer |
##### Responses
| Code | Description | Schema |
| ---- | ----------- | ------ |
| 200 | Update market. | [Market](#market) |
### Models
#### Beneficiary
Get list of user beneficiaries
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | integer | Beneficiary Identifier in Database | No |
| currency | string | Beneficiary currency code. | No |
| uid | string | Beneficiary owner | No |
| name | string | Human rememberable name which refer beneficiary. | No |
| description | string | Human rememberable description of beneficiary. | No |
| data | json | Bank Account details for fiat Beneficiary in JSON format.For crypto it's blockchain address. | No |
| state | string | Defines either beneficiary active - user can use it to withdraw moneyor pending - requires beneficiary activation with pin. | No |
| sent_at | string | Time when last pin was sent | No |
#### Balance
Queries the account balance for the given UID and currency.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| uid | string | The shared user ID. | No |
| balance | string | The account balance. | No |
| locked | string | The locked account balance. | No |
#### Deposit
Returns deposits as paginated collection.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| tid | integer | The shared transaction ID. | No |
| currency | string | The currency code. | No |
| uid | string | The shared user ID. | No |
| type | string | The deposit type (fiat or coin). | No |
| amount | string | The deposit amount. | No |
| state | string | The deposit state. «submitted» initial state. «canceled» deposit has been canceled by outer service. «rejected» deposit has been rejected by outer service.. «accepted» deposit has been accepted by outer service, money are loaded. | No |
| created_at | string | The datetime when deposit was created. | No |
| completed_at | string | The datetime when deposit was completed. | No |
| blockchain_txid | string | The transaction ID on the Blockchain (coin only). | No |
| blockchain_confirmations | string | The number of transaction confirmations on the Blockchain (coin only). | No |
| transfer_type | string | deposit transfer_type. | No |
#### Withdraw
Returns withdraws as paginated collection.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| tid | integer | The shared transaction ID. | No |
| uid | string | The shared user ID. | No |
| currency | string | The currency code. | No |
| note | string | The note for withdraw. | No |
| type | string | The withdraw type (fiat or coin). | No |
| amount | string | The withdraw amount excluding fee. | No |
| fee | string | The exchange fee. | No |
| rid | string | The beneficiary ID or wallet address on the Blockchain. | No |
| state | string | The withdraw state. «prepared» initial state, money are not locked. «submitted» withdraw has been allowed by outer service for further validation, money are locked. «canceled» withdraw has been canceled by outer service, money are unlocked. «accepted» system has validated withdraw and queued it for processing by worker, money are locked. «rejected» system has validated withdraw and found errors, money are unlocked. «processing» worker is processing withdraw as the current moment, money are locked. «skipped» worker skipped withdrawal in case of insufficient balance of hot wallet or it absence. «succeed» worker has successfully processed withdraw, money are subtracted from the account. «failed» worker has encountered an unhandled error while processing withdraw, money are unlocked. | No |
| created_at | string | The datetime when withdraw was created. | No |
| blockchain_txid | string | The transaction ID on the Blockchain (coin only). | No |
| transfer_type | string | withdraw transfer_type. | No |
#### Operation
Returns liabilities as paginated collection.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| code | string | The Account code which this operation related to. | No |
| currency | string | Operation currency ID. | No |
| credit | string | Operation credit amount. | No |
| debit | string | Operation debit amount. | No |
| uid | string | The shared user ID. | No |
| reference_type | string | The type of operations. | No |
| created_at | string | The datetime when operation was created. | No |
#### Order
Returns orders
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | integer | Unique order id. | No |
| member_id | integer | Member id. | No |
| uuid | string | Unique order UUID. | No |
| side | string | Either 'sell' or 'buy'. | No |
| ord_type | string | Type of order, either 'limit' or 'market'. | No |
| price | double | Price for each unit. e.g.If you want to sell/buy 1 btc at 3000 usd, the price is '3000.0' | No |
| avg_price | double | Average execution price, average of price in trades. | No |
| state | string | One of 'wait', 'done', or 'cancel'.An order in 'wait' is an active order, waiting fulfillment;a 'done' order is an order fulfilled;'cancel' means the order has been canceled. | No |
| market | string | The market in which the order is placed, e.g. 'btcusd'.All available markets can be found at /api/v2/markets. | No |
| created_at | string | Order create time in iso8601 format. | No |
| updated_at | string | Order updated time in iso8601 format. | No |
| origin_volume | double | The amount user want to sell/buy.An order could be partially executed,e.g. an order sell 5 btc can be matched with a buy 3 btc order,left 2 btc to be sold; in this case the order's volume would be '5.0',its remaining_volume would be '2.0', its executed volume is '3.0'. | No |
| remaining_volume | double | The remaining volume, see 'volume'. | No |
| executed_volume | double | The executed volume, see 'volume'. | No |
| maker_fee | double | Fee for maker. | No |
| taker_fee | double | Fee for taker. | No |
| trades_count | integer | Count of trades. | No |
| trades | [ [Trade](#trade) ] | Trades wiht this order. | No |
#### Trade
Returns trades as paginated collection.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | string | Trade ID. | No |
| price | double | Trade price. | No |
| amount | double | Trade amount. | No |
| total | double | Trade total (Amount * Price). | No |
| fee_currency | double | Currency user's fees were charged in. | No |
| fee | double | Percentage of fee user was charged for performed trade. | No |
| fee_amount | double | Amount of fee user was charged for performed trade. | No |
| market | string | Trade market id. | No |
| created_at | string | Trade create time in iso8601 format. | No |
| taker_type | string | Trade taker order type (sell or buy). | No |
| side | string | Trade side. | No |
| order_id | integer | Order id. | No |
#### Currency
Return currencies list.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | string | Currency code.<br>_Example:_ `"btc"` | No |
| name | string | Currency name<br>_Example:_ `"Bitcoin"` | No |
| description | string | Currency description<br>_Example:_ `"btc"` | No |
| homepage | string | Currency homepage<br>_Example:_ `"btc"` | No |
| price | string | Currency current price | No |
| explorer_transaction | string | Currency transaction exprorer url template<br>_Example:_ `"https://testnet.blockchain.info/tx/"` | No |
| explorer_address | string | Currency address exprorer url template<br>_Example:_ `"https://testnet.blockchain.info/address/"` | No |
| type | string | Currency type<br>_Example:_ `"coin"` | No |
| deposit_enabled | string | Currency deposit possibility status (true/false). | No |
| withdrawal_enabled | string | Currency withdrawal possibility status (true/false). | No |
| deposit_fee | string | Currency deposit fee<br>_Example:_ `"0.0"` | No |
| min_deposit_amount | string | Minimal deposit amount<br>_Example:_ `"0.0000356"` | No |
| withdraw_fee | string | Currency withdraw fee<br>_Example:_ `"0.0"` | No |
| min_withdraw_amount | string | Minimal withdraw amount<br>_Example:_ `"0.0"` | No |
| withdraw_limit_24h | string | Currency 24h withdraw limit<br>_Example:_ `"0.1"` | No |
| withdraw_limit_72h | string | Currency 72h withdraw limit<br>_Example:_ `"0.2"` | No |
| base_factor | string | Currency base factor<br>_Example:_ `100000000` | No |
| precision | string | Currency precision<br>_Example:_ `8` | No |
| position | integer | Currency position. | No |
| icon_url | string | Currency icon<br>_Example:_ `"https://upload.wikimedia.org/wikipedia/commons/0/05/Ethereum_logo_2014.svg"` | No |
| min_confirmations | string | Number of confirmations required for confirming deposit or withdrawal | No |
| code | string | Unique currency code. | No |
| min_collection_amount | string | Minimal deposit amount that will be collected<br>_Example:_ `"0.0000356"` | No |
| visible | string | Currency display possibility status (true/false). | No |
| subunits | integer | Fraction of the basic monetary unit. | No |
| options | json | Currency options. | No |
| created_at | string | Currency created time in iso8601 format. | No |
| updated_at | string | Currency updated time in iso8601 format. | No |
#### Market
Update market.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| id | string | Unique market id. It's always in the form of xxxyyy,where xxx is the base currency code, yyy is the quotecurrency code, e.g. 'btcusd'. All available markets canbe found at /api/v2/markets. | No |
| name | string | Market name. | No |
| base_unit | string | Market Base unit. | No |
| quote_unit | string | Market Quote unit. | No |
| min_price | double | Minimum order price. | No |
| max_price | double | Maximum order price. | No |
| min_amount | double | Minimum order amount. | No |
| amount_precision | double | Precision for order amount. | No |
| price_precision | double | Precision for order price. | No |
| state | string | Market state defines if user can see/trade on current market. | No |
| position | integer | Market position. | No |
| created_at | string | Market created time in iso8601 format. | No |
| updated_at | string | Market updated time in iso8601 format. | No |

File diff suppressed because it is too large Load Diff

1701
docs/api/swagger.json Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

390
docs/api/trading_api.md Normal file
View File

@@ -0,0 +1,390 @@
# Peatio REST API
Peatio REST API allows to access market data and manage trades using the custom-written software. The end goal is to allow users to create trading platforms on their own to create highly customised and advanced trading strategies.
## General API Information
### HTTP Return Codes
- HTTP 4XX return codes are used for malformed requests; the issue is on the sender's side.
- HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.
- HTTP 429 return code is used when breaking a request rate limit.
- HTTP 5XX return codes are used for internal errors; the issue is on deployment side. It is important to NOT treat this as a failure operation; the execution status is UNKNOWN and could have been a success.
### General Information on Endpoints
- All endpoints return either a JSON object or array.
- All time and timestamp related fields are in seconds.
### Endpoint security types
REST endpoints fall into two types the difference between the two being if the request is public, or requires authentication. In order to access the parts of the API which require authentication, you can use cookies or generate an API key and an API secret.
#### List of all user API endpoints you can find here ([user_api_docs](https://github.com/openware/peatio/blob/master/docs/api/peatio_user_api_v2.md))
#### Prerequisites
- install [httpie](https://httpie.org/doc#installation)
- install [curl](https://www.tecmint.com/install-curl-in-linux/)
## Public Endpoints Examples
Get list of avaliable currencies:
Example with httpie:
```bash
http GET https://your.domain/api/v2/peatio/public/markets
```
Expected response:
```json
[
{
"amount_precision": 5,
"base_unit": "eth",
"id": "ethusdt",
"max_price": "1000.0",
"min_amount": "0.00001",
"min_price": "0.01",
"name": "ETH/USDT",
"price_precision": 2,
"quote_unit": "usdt",
"state": "enabled"
},
{
"amount_precision": 6,
"base_unit": "btc",
"id": "btcusdt",
"max_price": "12000.0",
"min_amount": "0.0001",
"min_price": "5000.0",
"name": "BTC/USDT",
"price_precision": 4,
"quote_unit": "usdt",
"state": "enabled"
}
]
```
Example with curl:
```bash
curl -X GET https://your.domain/api/v2/peatio/public/markets
```
Expected response:
```bash
[
{
"amount_precision": 5,
"base_unit": "eth",
"id": "ethusdt",
"max_price": "1000.0",
"min_amount": "0.00001",
"min_price": "0.01",
"name": "ETH/USDT",
"price_precision": 2,
"quote_unit": "usdt",
"state": "enabled"
},
{
"amount_precision": 6,
"base_unit": "btc",
"id": "btcusdt",
"max_price": "12000.0",
"min_amount": "0.0001",
"min_price": "5000.0",
"name": "BTC/USDT",
"price_precision": 4,
"quote_unit": "usdt",
"state": "enabled"
}
]
```
## Authentication
For get access to private endpoints you can use cookies or generate API keys via UI (highly recommended) or API.
### Authentication with cookies (more for test purposes)
1. Create and save session cookies using httpie
```bash
http --session barong_session https://your.domain/api/v2/barong/identity/sessions \
email=your@email.com password=changeme
```
2. Call private endpoint with created session
```bash
http --session barong_session https://your.domain.com/api/v2/peatio/account/balances
```
Expected response:
```bash
[
{
"balance": "1.4995",
"currency": "eth",
"locked": "0.0"
},
{
"balance": "99.0",
"currency": "usd",
"locked": "0.0"
}
]
```
### Authentication with API keys
#### How to create API key?
1. Using UI
1. Enable 2FA
2. Find API keys section (often located on profile page).
3. Create your API key and securely save API Key and Secret
2. Using API (use this option in case your frontend doesn't support API keys feature)
1. Login into your account using httpie
```bash
http --session barong_session https://your.domain/api/v2/barong/identity/sessions \
email=your@email.com password=changeme otp_code=000000
```
2. Create your API key
```bash
http --session barong_session https://your.domain.com/api/v2/barong/resource/api_keys \
algorithm=HS256 totp_code=681757
```
Expected response:
```ruby
{
"algorithm": "HS256",
"created_at": "2019-12-23T12:22:15Z",
"kid": "61d025b8573501c2", # API Key
"scope": [],
"secret": {
"auth": null,
"data": {
"value": "2d0b4979c7fe6986daa8e21d1dc0644f" # Secret
},
"lease_duration": 2764800,
"lease_id": "",
"metadata": null,
"renewable": false,
"warnings": null,
"wrap_info": null
},
"state": "active",
"updated_at": "2019-12-23T12:22:15Z"
}
```
3. Securely save API Key and Secret
#### How to use API key?
Before calling private endpoint you will need to generate three headers:
`X-Auth-Apikey` - API key (from previous step)
`X-Auth-Nonce` - A nonce is an arbitrary number that can be used just once. In our environment you *MUST* use a millisecond timestamp in UTC time. Read more about it [here](https://en.wikipedia.org/wiki/Cryptographic_nonce).
```bash
date +%s%3N
1584087661035
```
`X-Auth-Signature` - HMAC-SHA256 signature calculated using concatenation of X-Auth-Nonce and X-Auth-Apikey
```ruby
require 'openssl'
nonce = '1584087661035'
api_key = 'changeme' # API Key from 'How to create API key section ?'
secret = 'changeme' # Secret from 'How to create API key section ?'
OpenSSL::HMAC.hexdigest("SHA256", secret, nonce + api_key)
# => "6cc108cb3427b655ccf0870fc7fa807ef3756506d4db3f3c93f8d4cd8ef0e611"
```
```bash
curl -X GET https://your.domain.com/api/v2/peatio/account/balances \
-H "X-Auth-Apikey: changeme" \
-H "X-Auth-Nonce: changeme" \
-H "X-Auth-Signature: changeme"
```
Expected response:
```bash
[
{
"balance": "1.4995",
"currency": "eth",
"locked": "0.0"
}
]
```
Expected response:
```bash
curl -X GET https://your.domain.com/api/v2/peatio/market/orders \
-H "X-Auth-Apikey: changeme" \
-H "X-Auth-Nonce: changeme" \
-H "X-Auth-Signature: changeme"
```
```bash
[
{
"avg_price": "168.0",
"created_at": "2020-01-28T15:14:02+01:00",
"executed_volume": "0.1",
"id": 6291918,
"market": "ethusd",
"ord_type": "limit",
"origin_volume": "0.1",
"price": "168.0",
"remaining_volume": "0.0",
"side": "buy",
"state": "done",
"trades_count": 1,
"updated_at": "2020-03-12T09:17:32+01:00"
}
]
```
## Step By step guide from authentication to create | cancel order with API keys
1. Generate API keys (see Authentication with API keys section)
2. Create order
```bash
http POST https://your.domain.com/api/v2/peatio/market/orders \
"X-Auth-Apikey: changeme" \
"X-Auth-Nonce: changeme" \
"X-Auth-Signature: changeme" \
market=ethusd side=buy volume=31 ord_type=limit price=160.82
```
Expected response:
```bash
{
"avg_price": "0.0",
"created_at": "2020-03-12T17:01:56+01:00",
"executed_volume": "0.0",
"id": 10440269,
"market": "ethusd",
"ord_type": "limit",
"origin_volume": "31.0",
"price": "160.82",
"remaining_volume": "31.0",
"side": "buy",
"state": "pending",
"trades_count": 0,
"updated_at": "2020-03-12T17:01:56+01:00"
}
```
3. Check trade history
```bash
http POST https://your.domain.com/api/v2/peatio/market/trades \
"X-Auth-Apikey: changeme" \
"X-Auth-Nonce: changeme" \
"X-Auth-Signature: changeme" \
```
Expected response:
```bash
{
"amount": "5.0",
"created_at": "2020-03-12T17:01:56+01:00",
"fee": "0.002",
"fee_amount": "0.01",
"fee_currency": "eth",
"id": 1834499,
"market": "ethusd",
"order_id": 10440269,
"price": "160.82",
"side": "buy",
"taker_type": "buy",
"total": "804.1"
}
```
4. Check active orders
```bash
curl -X GET https://your.domain.com/api/v2/peatio/market/orders\?state\=wait \
-H "X-Auth-Apikey: changeme" \
-H "X-Auth-Nonce: changeme" \
-H "X-Auth-Signature: changeme"
```
Expected response:
```bash
[
{
"avg_price": "160.82",
"created_at": "2020-03-12T17:01:56+01:00",
"executed_volume": "26.35649",
"id": 10440269,
"market": "ethusd",
"ord_type": "limit",
"origin_volume": "31.0",
"price": "160.82",
"remaining_volume": "4.64351",
"side": "buy",
"state": "wait",
"trades_count": 6,
"updated_at": "2020-03-12T17:01:56+01:00"
}
]
```
5. Cancel active order
```bash
curl -X GET https://your.domain.com/api/v2/peatio/market/orders/10440269/cancel \
-H "X-Auth-Apikey: changeme" \
-H "X-Auth-Nonce: changeme" \
-H "X-Auth-Signature: changeme"
```
Expected response
```bash
{
"avg_price": "160.82",
"created_at": "2020-03-12T17:01:56+01:00",
"executed_volume": "26.35649",
"id": 10440269,
"market": "ethusd",
"ord_type": "limit",
"origin_volume": "31.0",
"price": "160.82",
"remaining_volume": "4.64351",
"side": "buy",
"state": "wait",
"trades_count": 6,
"updated_at": "2020-03-12T17:01:56+01:00"
}
```

293
docs/api/websocket_api.md Normal file
View File

@@ -0,0 +1,293 @@
# Peatio WebSocket API
Peatio WebSocket API connections are handled by Ranger service provided by
[peatio gem](https://github.com/rubykube/peatio-core).
### API
There are two types of channels:
* Public: accessible by anyone
* Private: accessible only by given member
GET request parameters:
| Field | Description | Multiple allowed |
|----------|-------------------------------------|------------------|
| `stream` | List of streams to be subscribed on | Yes |
List of supported public streams:
* [`<market>.ob-inc`](#order-book) market order-book update
* [`<market>.trades` ](#trades)
* [`<market>.kline-PERIOD` ](#kline-point) (available periods are "1m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d", "3d", "1w")
* [`global.tickers`](#tickers)
List of supported private streams (requires authentication):
* [`order`](#order)
* [`trade`](#trade)
You can find a format of these events below in the doc.
### Authentication
Authentication happens on websocket message with following JSON structure.
```JSON
{
"jwt": "Bearer <Token>"
}
```
If authentication was done, server will respond successfully
```JSON
{
"success": {
"message": "Authenticated."
}
}
```
Otherwise server will return an error
```JSON
{
"error": {
"message": "Authentication failed."
}
}
```
If authentication JWT token has invalid type, server return an error
```JSON
{
"error": {
"message": "Token type is not provided or invalid."
}
}
```
If other error occurred during the message handling server throws an error
```JSON
{
"error": {
"message": "Error while handling message."
}
}
```
**Note:** Peatio websocket API supports authentication only Bearer type of JWT token.
**Example** of authentication message:
```JSON
{
"jwt": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
}
```
### Streams subscription
#### Using parameters
You can specify streams to subscribe to by passing the `stream` GET parameter in the connection URL. The parameter can be specified multiple times for subscribing to multiple streams.
example:
```
wss://demo.openware.com/api/v2/ranger/public/?stream=global.tickers&stream=ethusd.trades
```
This will subscribe you to *tickers* and *trades* events from *ethusd* market once the connection is established.
#### Subscribe and unsubscribe events
You can manage the connection subscriptions by send the following events after the connection is established:
Subscribe event will subscribe you to the list of streams provided:
```json
{"event":"subscribe","streams":["ethusd.trades","ethusd.ob-inc"]}
```
The server confirms the subscription with the following message and provides the new list of your current subscrictions:
```json
{"success":{"message":"subscribed","streams":["global.tickers","ethusd.trades","ethusd.ob-inc"]}}
```
Unsubscribe event will unsubscribe you to the list of streams provided:
```json
{"event":"unsubscribe","streams":["ethusd.trades","ethusd.ob-inc"]}
```
The server confirms the unsubscription with the following message and provides the new list of your current subscrictions:
```json
{"success":{"message":"unsubscribed","streams":["global.tickers","ethusd.kline-15m"]}}
```
### Public streams
#### Order-Book
This stream sends a snapshot of the order-book at the subscription time, then it sends increments. Volumes information in increments replace the previous values. If the volume is zero the price point should be removed from the order-book.
Register to stream `<market>.ob-inc` to receive snapshot and increments messages.
Example of order-book snapshot:
```json
{
"eurusd.ob-snap":{
"asks":[
["15.0","21.7068"],
["20.0","100.2068"],
["20.5","30.2068"],
["30.0","21.2068"]
],
"bids":[
["10.95","21.7068"],
["10.90","65.2068"],
["10.85","55.2068"],
["10.70","30.2068"]
]
}
}
```
Example of order-book increment message:
```json
{
"eurusd.ob-inc":{
"asks":[
["15.0","22.1257"]
]
}
}
```
#### Trades
Here is structure of `<market>.trades` event expose as array with trades:
| Field | Description |
| -------------- | -------------------------------------------- |
| `tid` | Unique trade tid. |
| `taker_type` | Taker type of trade, either `buy` or `sell`. |
| `price` | Price for the trade. |
| `amount` | The amount of trade. |
| `created_at` | Trade create time. |
#### Kline point
Kline point as array of numbers:
1. Timestamp.
2. Open price.
3. Max price.
4. Min price.
5. Last price.
6. Period volume
Example:
```ruby
[1537370580, 0.0839, 0.0921, 0.0781, 0.0845, 0.5895]
```
#### Tickers
Here is structure of `global.tickers` event expose as array with all markets pairs:
| Field | Description |
| -----------------------| ------------------------------- |
| `at` | Date of current ticker. |
| `name` | Market pair name. |
| `base_unit` | Base currency. |
| `quote_unit` | Quote currency. |
| `low` | Lowest price in 24 hours. |
| `high` | Highest price in 24 hours. |
| `last` | Last trade price. |
| `open` | Last trade from last timestamp. |
| `close` | Last trade price. |
| `volume` | Volume in 24 hours. |
| `sell` | Best price per unit. |
| `buy` | Best price per unit. |
| `avg_price` | Average price for last 24 hours.|
| `price_change_percent` | Average price change in percent.|
### Private streams
#### Order
Here is structure of `Order` event:
| Field | Description |
| ------------------ | ------------------------------------------------------------ |
| `id` | Unique order id. |
| `market` | The market in which the order is placed. (In peatio `market_id`) |
| `order_type` | Order type, either `limit` or `market`. |
| `price` | Order price. |
| `avg_price` | Order average price. |
| `state` | One of `wait`, `done`, `reject` or `cancel`. |
| `origin_volume` | The amount user want to sell/buy. |
| `remaining_volume` | Remaining amount user want to sell/buy. |
| `executed_volume` | Executed amount for current order. |
| `created_at` | Order create time. |
| `updated_at` | Order create time. |
| `trades_count` | Trades with this order. |
| `kind` | Type of order, either `bid` or `ask`. (Deprecated) |
| `at` | Order create time. (Deprecated) (In peatio `created_at`) |
#### Trade
Here is structure of `Trade` event:
| Field | Description |
| ------------ | ------------------------------------------------------------ |
| `id` | Unique trade identifier. |
| `price` | Price for each unit. |
| `amount` | The amount of trade. |
| `total` | The total of trade (volume * price). |
| `market` | The market in which the trade is placed. (In peatio market_id) |
| `side` | Type of order in trade that related to current user `sell` or `buy`. |
| `taker_type` | Order side of the taker for the trade, either `buy` or `sell`. |
| `created_at` | Trade create time. |
| `order_id` | User order identifier in trade. |
### Development
Start ranger websocket server using following command in peatio-core gem:
```bash
$ ./bin/peatio service start ranger
```
Now we can test authentication with [wscat](https://github.com/websockets/wscat):
#### Connect to public channel:
```bash
$ wscat -n -c 'ws://ws.app.local:8080/api/ranger/v2?stream=usdeth'
```
#### Connect to private channel:
Authorization header will be injected automatically by ambassador so we could subscribe to private channels.
```bash
$ wscat -n -c 'ws://ws.app.local:8080/api/ranger/v2?stream=trade'
```
### Examples
There is also [example of working with Ranger service using NodeJS.](https://github.com/rubykube/ranger-example-nodejs)

135
docs/architecture.md Normal file
View File

@@ -0,0 +1,135 @@
# OpenDAX Crypto Platform Architecture (OCP)
## System Overview
OpenDAX Crypto-Platform, is a distribution of component working together to form
a crypto-currency cluster on Kubernetes.
## System Requirements
* Amazon AWS, Google Cloud GCP, Azure account
* Kubernetes cluster deployed using Kite
* MySQL 5.7 Highly available (RDS / Cloud SQL)
* Blockchain services or nodes running in VM
* RabbitMQ service running in the cluster or in VM
## Component Description
### Kite
Kite is a dev/ops framework for bootstraping any cloud provider and deploy a stack
using infrastructure as code best practices.
Kite 2.0 is a modular structure leveraging git and terraform with multi-environment management.
[Kite project](https://github.com/rubykube/kite)
#### Terraform
Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.
Kite uses terraform modules for initial configuration of the cloud account. We recommend using terraform for IAM config, VPC creation, networks and firewall.
[Terraform project](https://www.terraform.io/)
#### Bosh and Concourse
BOSH is a project that unifies release engineering, deployment, and lifecycle management of small and large-scale cloud software. BOSH can provision and deploy software over hundreds of VMs. It also performs monitoring, failure recovery, and software updates with zero-to-minimal downtime.
Kite and RKCP use Bosh for deploying blockchain nodes as a service.
Components managed by bosh are:
* Vault
* Bitcoin / Dash blockchain nodes
* Concourse CI
* RabbitMQ
* Prometheus with Grafana for monitoring
[Bosh project](https://bosh.io/)
#### Vault
Vault is a tool for securely accessing secrets. A secret is anything that you want to tightly control access to, such as API keys, passwords, or certificates. Vault provides a unified interface to any secret, while providing tight access control and recording a detailed audit log.
RKCP rely mainly on vault for keeping secrets, wallets secrets, certificates and OTP seeds.
[Vault project](https://www.vaultproject.io/)
#### Kubernetes
Kubernetes is a portable, extensible open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available.
Google open-sourced the Kubernetes project in 2014. Kubernetes is built upon a decade and a half of experience that Google has with running production workloads at scale, combined with best-of-breed ideas and practices from the community.
Kubernetes is the foundation of the RK Crypto-Platform (RKCP), we levarage all the features for auto-healing, scaling design and fail over.
We only recommend Kubernetes for production environments.
[Kubernetes project](https://www.kubernetes.io)
### Peatio
Peatio act as the main Accounting gateway between Fiat and Crypto-Currencies, Peatio is in charge of maintaining the Member balance for engaging trading activities.
We only use peatio as an API, we only configure it per deployments but continue using the vanilla open-source Peatio.
We build a docker container from sources available on docker hub rubykube/peatio.
We ship weekly improvements on Peatio container, by using a fork you won't be able to upgrade your deployments with newest features.
Our goal and roadmap is to provide advanced API endpoints in order to be able to customize all behaviors around Peatio such as:
* Plug in payment gateways
* Plug in liquidity providers
* Replace Trade matching worker
* Consume Peatio events using Event API
[Peatio project](https://github.com/rubykube/peatio)
#### OpenDAX Docker compose
OpenDAX compose is the recommended development, test and integration environment for new developers.
Bundler 2.0.2
[OpenDAX Peatio](https://github.com/openware/opendax)
#### Coinhub
Blockchain gateway from Kubernetes to external Blockchain APIs.
[Coinhub project](https://github.com/rubykube/coinhub)
### Barong
Barong is a KYC OAuth 2.0 provider.
Barong replace the KyC, 2FA, phone verification from legacy Peatio.
Barong manage roles and KyC level across all applications from the RKCP.
It's easy to extend by using the EventAPI or REST API.
[Barong project](https://github.com/rubykube/barong)
### Cryptobase
Cryptobase is a base boilerplate Angular/React/Vue.js implementation of the Peatio frontend.
Unfortunately, we don't have an open-source implementation yet.
### Arke
Arke is the missing tool for connecting a liquidity network on your exchange.
Arke is an Open-Source Crypto-Currency Arbitrage platform.
## Stage and QA Environment
We recommend deploying using kite a "stage" environment in which you need to pull newest containers
from the RKCP distribution and run integration testing with your own components.
We recommend using the following namespaces:
* `stage` will hold latest containers
* `platform-tools` will run a Jenkins helm chart for test automation
* `feature-name` namespace for a single micro-service deployment which can use stage micro-services as backend for RC testing
## Production Environment
In production environment it is recommended that Vault deployment is hardened in an isolated VM, and make sure most dev/ops cannot access nor administer Vault.
Make sure all wallets have multi-signature and offload regularly on cold wallets.
Do not leave seeds, private keys or passphrase at the reach of developers, system administrators and eventuals hackers.

View File

@@ -0,0 +1,11 @@
# Getting Bitcoins in Testnet
When system will generate your personal BTC deposit address you may want to deposit some coins to it. Since Peatio uses Bitcoin Testnet by default you can use any existing public faucets to get coins:
* [https://testnet.manu.backend.hamburg/faucet](https://testnet.manu.backend.hamburg/faucet)
* [http://tpfaucet.appspot.com](http://tpfaucet.appspot.com)
* [https://kuttler.eu/en/bitcoin/btc/faucet](https://kuttler.eu/en/bitcoin/btc/faucet)
* [http://bitcoinfaucet.uo1.net](http://bitcoinfaucet.uo1.net)
* [https://testnet.coinfaucet.eu/en](https://testnet.coinfaucet.eu/en)
Open any public faucet in the browser, copy your deposit address and paste it to the field, optionally solve captcha and submit the form. Wait until transaction will receive enough confirmations. Then you will see your balance at «Funds».

330
docs/coins/development.md Normal file
View File

@@ -0,0 +1,330 @@
# Currency plugin development.
Peatio Plugin API v2 gives ability to extend Peatio with any coin
which fits into basic [Blockchain](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract) and [Wallet](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract)
interfaces described inside [peatio-core](https://github.com/rubykube/peatio-core) gem.
## Development.
### Start from reading Blockchain and Wallet doc.
You need to be familiar with [Blockchain](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract)
and [Wallet](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract) interfaces.
**Note:** *you can skip optional methods if they are not supported by your coin.*
### Coin API research.
First of all need to start your coin node locally or inside VM and try to access it via HTTP e.g. using `curl` or `http`.
You need to study your coin API to get list of calls for implementing [Blockchain](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract) and
[Wallet](https://www.rubydoc.info/gems/peatio/0.5.0/Peatio/Blockchain/Abstract) interfaces.
**Note:** *single method may require multiple API calls.*
We next list of JSON RPC methods for Bitcoin integration:
* getbalance
* getblock
* getblockcount
* getblockhash
* getnewaddress
* listaddressgroupings
* sendtoaddress
For Ethereum Blockchain (ETH, ERC20) we use next list of methods:
* eth_blockNumber
* eth_getBalance
* eth_call
* eth_getTransactionReceipt
* eth_getBlockByNumber
* personal_newAccount
* personal_sendTransaction
### Ruby gem development.
During this step you will create your own ruby gem for implementing your coin Blockchain and Wallet classes.
We will use [peatio-litecoin](https://github.com/rubukybe/peatio-litecoin) as example.
My advice is to clone it and use as plugin development guide.
For more currencies examples check [Bitcoin](../../lib/peatio/bitcoin) and [Ethereum](../../lib/peatio/ethereum) implementation.
1. ***Create a new gem. And update .gemspec.*** 💎
```bash
bundle gem peatio-litecoin
```
**Note:** *there is no requirements for gem naming and module hierarchy.*
2. ***Add your gem dependencies to .gemspec.*** 🛠
I use the next list of gems (you could specify preferred by you inside you gem):
```ruby
spec.add_dependency "activesupport", "~> 5.2.3"
spec.add_dependency "better-faraday", "~> 1.0.5"
spec.add_dependency "faraday", "~> 0.15.4"
spec.add_dependency "memoist", "~> 0.16.0"
spec.add_dependency "peatio", "~> 0.6.1" # Required.
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "mocha", "~> 1.8"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "webmock", "~> 3.5"
```
**Note:** *peatio gem is required.*
3. ***Install your dependencies.*** ⚙
```bash
bundle install
```
4. ***Save responses in spec/resources.*** 📥
You could start from saving few responses and then extend your mock factory.
Peatio-litecoin spec/resources directory has the following structure:
```bash
tree spec/resources
spec/resources
├── getbalance
│   └── response.json
├── getblock
│   └── 40500.json
├── getblockcount
│   └── 40500.json
├── getblockhash
│   └── 40500.json
├── getnewaddress
│   └── response.json
├── listaddressgroupings
│   └── response.json
├── methodnotfound
│   └── error.json
└── sendtoaddress
└── response.json
```
5. ***Prepare your gem structure.*** 📐
You could organize files and directories as you wish.
Peatio-litecoin has the following lib and spec structure:
```bash
tree lib
lib
└── peatio
├── litecoin
│   ├── blockchain.rb
│   ├── client.rb
│   ├── hooks.rb
│   ├── railtie.rb
│   ├── version.rb
│   └── wallet.rb
└── litecoin.rb
tree spec/peatio
spec/peatio
├── litecoin
│   ├── blockchain_spec.rb
│   ├── client_spec.rb
│   └── wallet_spec.rb
└── litecoin_spec.rb
```
6. ***Start with your coin client implementation.*** 🥚
First of all try to find reliable ruby client for your coin and implement own if there is no such.
We don't provide client interface so you could construct client in the way it's convenient for you
but note that it's your gem base because you will use it widely during Blockchain and Wallet implementation.
7. ***Try to call API with your client. Use ./bin/console for this.*** 📮
```ruby
client = Peatio::Litecoin::Client.new('http://user:password@127.0.0.1:19332') # => #<Peatio::Litecoin::Client:0x00007fca61d82650 @json_rpc_endpoint=#<URI::HTTP http://user:password@127.0.0.1:19332>>
client.json_rpc(:getblockcount) # => 1087729
client.json_rpc(:getnewaddress) # => "QQPyC9uTQ1YKu3V1Dr4rNqHkHgJG3qr8JC"
```
8. ***Use spec/resources for client testing.*** 🧰
E.g. specs for peatio-litecoin client:
```bash
bundle exec rspec spec/peatio/litecoin/client_spec.rb
Peatio::Litecoin::Client
initialize
should not raise Exception
json_rpc
getblockcount
should not raise Exception
should eq 40500
methodnotfound
should raise Peatio::Litecoin::Client::ResponseError with "Method not found (-32601)"
notfound
should raise Peatio::Litecoin::Client::Error
connectionerror
should raise Peatio::Litecoin::Client::ConnectionError
Finished in 0.01355 seconds (files took 1.11 seconds to load)
6 examples, 0 failures
```
9. ***Implement Blockchain::Abstract interface required methods.*** 🔗
```ruby
module Peatio
module Litecoin
class Blockchain < Peatio::Blockchain::Abstract
# Your custom logic goes here.
end
end
end
```
I suggest using the next order of methods implementation:
* initialize
* configure
* latest_block_number
* fetch_block!
* load_balance_of_address! (optional)
10. ***Mock API calls using spec/resources and test your blockchain.*** 🛡
E.g. specs for peatio-litecoin blockchain:
```bash
Peatio::Litecoin::Blockchain
features
defaults
override defaults
custom feautures
configure
default settings
currencies and server configuration
latest_block_number
returns latest block number
raises error if there is error in response body
build_transaction
three vout tx
builds formatted transactions for passed transaction
multiple currencies
builds formatted transactions for passed transaction per each currency
single vout transaction
builds formatted transactions for each vout
fetch_block!
builds expected number of transactions
all transactions are valid
load_balance_of_address!
address with balance is defined
requests rpc listaddressgroupings and finds address balance
requests rpc listaddressgroupings and finds address with zero balance
address is not defined
requests rpc listaddressgroupings and do not find address
client error is raised
raise wrapped client error
Finished in 0.02604 seconds (files took 1.14 seconds to load)
16 examples, 0 failures
```
11. ***Implement Wallet::Abstract interface required methods.*** 💸
```ruby
module Peatio
module Litecoin
class Wallet < Peatio::Blockchain::Abstract
# Your custom logic goes here.
end
end
end
```
I suggest using the next order of methods implementation:
* initialize
* configure
* create_address!
* create_transaction!
* load_balance! (optional)
12. ***Mock API calls using spec/resources and test your wallet.*** 🔐️
E.g. specs for peatio-litecoin wallet:
```bash
Peatio::Litecoin::Wallet
configure
requires wallet
requires currency
sets settings attribute
create_address!
request rpc and creates new address
create_transaction!
requests rpc and sends transaction without subtract fees
load_balance!
requests rpc with getbalance call
Finished in 0.01205 seconds (files took 1.08 seconds to load)
6 examples, 0 failures
```
13. ***Register your plugin blockchain and wallet to make it accessible by Peatio.*** ®
```ruby
Peatio::Blockchain.registry[:litecoin] = Litecoin::Blockchain.new
Peatio::Wallet.registry[:litecoind] = Litecoin::Wallet.new
```
For more info check hooks.rb and railtie.rb.
**Note:** *You could just copy paste this files and change wallet and blockchain names.*
14. ***Test your plugin inside peatio eco system.*** 🧪
Every story which touch blockchain or wallet should work successfully:
* deposit address generation
* deposit detection
* blockchain synchronization
* deposit collection
* withdraw creation
* withdraw confirmation
15. ***Document your plugin integration steps.*** 📝
Documentation folder for Litecoin has the following structure:
```bash
docs
├── integration.md
├── json-rpc.md
└── testnet.md
```
* integration.md
Describe full plugin integration flow in integration.md.
**Image Build** and **Peatio Configuration** sections are required.
**Don't forget to describe custom steps here e.g.**
*"Send some XRP for wallet activation"* or *"For ERC20 integration fee wallet with ETH is required"*.
* json-rpc.md
List all API calls used for gem development here with examples and description.
* testnet.md
Give instructions how to get coins in testent.
**Note:** it's minimalistic doc structure. More doc is more love for your plugin.
16. Contact us to review your plugin and add to [approved plugins list](../plugins.md).
For doing it left comment with your plugin link and short description [here](https://github.com/rubykube/peatio/issues/2212).

10
docs/coins/erc20/erc20.md Normal file
View File

@@ -0,0 +1,10 @@
# Getting ERC20 tokens in Rinkeby Testnet
When system will generate your personal ERC20 deposit address you may want to deposit some coins to it. Peatio recommends Rinkeby Ethereum Testnet.
To get test tokens in Rinkeby network:
1) to get a TRST (WeTrust) coins in the Testnet, follow the instructions [here](https://github.com/WeTrustPlatform/erc20faucet-contracts).
2) to get a HUR (Hurify) coins in the Testnet, follow the instructions [here](https://medium.com/@Hurify/metamask-installation-and-adding-hur-tokens-on-test-network-for-platform-evaluation-bb7438bf54cd).

View File

@@ -0,0 +1,24 @@
# Getting Ethers in Rinkeby Testnet
Peatio generates a single ETH wallet for every user.
For testing you can connect peatio to ethereum testnet like Rinkeby, Kovan, Ropsten or Goerli.
To get test coins in Rinkeby network do the following:
1. Generate your deposit address.
2. Copy it.
3. Open [Rinkeby faucet](https://www.rinkeby.io/#faucet).
4. Read paragraph «How does this work?».
5. Follow the guide you have just read.
6. Wait until transaction will receive enough confirmations. Then you will see your balance at «Funds». You can use [block explorer](https://rinkeby.etherscan.io/) to track the status of your transaction.
Useful links:
* [Rinkeby homepage](https://www.rinkeby.io/)
* [Rinkeby network block explorer](https://rinkeby.etherscan.io/)
* [Rinkeby faucet](https://www.rinkeby.io/#faucet)
# Getting Ethers in Kovan Testnet
To get ETH in Kovan network you will need GitHub account. Go to https://gitter.im/kovan-testnet/faucet, sign in and post message with your ETH address. In few minutes you will get money automatically. Don't post too often or you can be banned.

7
docs/coins/plugins.md Normal file
View File

@@ -0,0 +1,7 @@
# List of coin plugins approved by RubyKube
* [Litecoin](https://github.com/rubykube/peatio-litecoin)
* [Ripple](https://github.com/rubykube/peatio-ripple)
* [Bicoin Cash](https://github.com/rubykube/peatio-bitcoincash)
## For plugin integration check doc/integration.md of specific plugin.

11
docs/databases/mariadb.md Normal file
View File

@@ -0,0 +1,11 @@
## How to use Peatio with MariaDB
Peatio supports MariaDB 10.2.7 and upper.
MariaDB json types are not well supported by Rails, to make the application work properly you need to enable explicit serialization and deserialization of JSON fields.
To do so, set the following environment variable:
```bash
export DATABASE_SUPPORT_JSON=false
```

View File

@@ -0,0 +1,9 @@
## How to use Peatio with PostgreSQL
Export the following variables:
```bash
export DATABASE_ADAPTER="postgresql"
export DATABASE_PORT="5432"
export DATABASE_COLLATION=""
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

@@ -0,0 +1,13 @@
### In Peatio 2.4 introduced InfluxDB for storing trades and building k-lines. For import local historical trades you will need to process severall rake tasks
1. Import trades to the InfluxDB:
```bash
bundle exec rake import:trade_to_influx
```
2. Build k-lines:
```bash
bundle exec rake import:influx_build_candles
```

View File

@@ -0,0 +1,47 @@
### Starting from Peatio from 2.3.48 wallets settings stores in Vault. Since all settings should be moved to Vault, we need to recreate wallets in Peatio.
To do this, follow these steps:
1. Execute into Rails Console and run:
```ruby
result = Wallet.all.map { |m| m.attributes.except('created_at', 'updated_at') }.map { |r| r.transform_values! { |v| v.is_a?(BigDecimal) ? v.to_f : v } }
result.each do |w|
w.except!('settings_encrypted', 'id')
w['settings'] = Wallet.find_by(address: w['address']).settings
w['kind'] = w['kind'].to_s
end
File.open("config/seed/wallets_backup.yml","w") do |file|
file.write result.to_yaml
end
Wallet.delete_all
```
1. Put content of the `config/seed/wallets_backup.yml` in the `config/seed/wallets.yml`.
2. Change the Peatio version.
3. Run `rake db:migrate db:seed`. It will migrate DB and seed wallets into Peatio.
### If you are using Peatio 2.3.62 or higher and you need to move to another Vault instance you will need to export wallets settings and user payment_addresses and import it to the new environment.
To do this you will need to process this steps:
1. Export wallet settings:
```ruby
bundle exec rake export:wallets
```
2. Export user addresses:
```ruby
bundle exec rake export:addresses
```
3. Put content of the `config/seed/wallets_backup.yml` in the `config/seed/wallets.yml`.
4. Change the Peatio version.
5. Run `rake db:migrate db:seed`. It will migrate DB and seed wallets into Peatio.
6. Import user addresses:
```ruby
bundle exec rake import:addresses['file_name.csv']
```

0
docs/ops/ci.md Normal file
View File

View File

@@ -0,0 +1,3 @@
# Deploy Peatio with Docker
This document is in progress...

View File

@@ -0,0 +1,76 @@
# Deploying Peatio on [Kubernetes](https://kubernetes.io/)
## Overview
1. [Dependencies](#dependencies)
2. [Configuration](#configuration)
3. [Installing the chart](#installing-the-chart)
3. [Getting help](#getting-help)
## Dependencies
Peatio has 3 main dependencies:
- [MySQL](https://www.mysql.com/)
- [Redis](https://redis.io/)
- [RabbitMQ](https://www.rabbitmq.com/)
If you don't have them installed yet, you can check our [helm charts repo](https://charts.peatio.tech/).
## Configuration
All the configuration goes in `config/charts/peatio/values.yaml`. It has many helpful comments, but in this section we have more details about each config option.
| Name | Default Value | Description |
| ------------------------- | ------------------------------ | ----------------------------- |
| `replicaCount` | `1` | Number of pod's replicas |
| `image.repository` | `"rubykube/peatio"` | Image repo |
| `image.tag` | `"0.2.2"` | Image version |
| `image.pullPolicy` | `"IfNotPresent"` | Image pull polucy |
| `service.name` | `"peatio"` | Service name |
| `service.type` | `"ClusterIP"` | Service type |
| `service.externalPort` | `8080` | Service external port |
| `service.internalPort` | `8080` | Service internal port |
| `ingress.enabled` | `false` | Enable or disable the ingress |
| `ingress.hosts` | `["peatio.local"]` | The virtual hosts names |
| `ingress.annotations` | see `values.yaml` | Ingress annotations |
| `ingress.tls.secretName` | `"peatio-tls"` | TLS secret name |
| `ingress.tls.hosts` | `["peatio.local"]` | TLS virtual hosts names |
| `resources.limits.cpu` | `"100m"` | CPU resource requests |
| `resources.limits.memory` | `"128Mi"` | Memory resource limits |
| `resources.limits.cpu` | `"100m"` | CPU resource requests |
| `resources.limits.memory` | `"128Mi"` | Memory resource requests |
| `peatio.env` | see `application.yml` | Peatio environment config |
| `db.host` | `"%current-release%-db"` | Your MySQL host |
| `db.user` | `"root"` | MySQL user |
| `db.password` | `nil` | MySQL password |
| `redis.host` | `"%current-release%-redis"` | Your Redis host |
| `redis.password` | `nil` | Redis password |
| `rabbitmq.host` | `"%current-release%-rabbitmq"` | Your RabbitMQ host |
| `rabbitmq.port` | `5672` | RabbitMQ port |
| `rabbitmq.username` | `nil` | RabbitMQ username |
| `rabbitmq.password` | `nil` | RabbitMQ password |
## Installing the chart
This one is simple:
```shell
helm install config/peatio/charts
```
If you want use `helm package` and external values file, try this:
```shell
$ helm package
Successfully packaged chart and saved it to: peatio-0.1.0.tgz
$ helm install peatio-0.1.0.tgz -f path/to/your/values.yaml
NAME: random-name
...
```
That's all you need to deploy peatio on kubernetes.
## Getting help
If you got any trouble with this deployment, please [open an issue](https://github.com/rubykube/peatio/issues/new). If you want external devops support with peatio, contact hello@peatio.tech.

209
docs/ops/deploy/ubuntu.md Normal file
View File

@@ -0,0 +1,209 @@
# Deploy production server on Ubuntu 14.04
### Overview
1. Setup deploy user
2. Install [Ruby](https://www.ruby-lang.org/en/)
3. Install [MySQL](http://www.mysql.com/)
4. Install [Redis](http://redis.io/)
5. Install [RabbitMQ](https://www.rabbitmq.com/)
6. Install [Bitcoind](https://en.bitcoin.it/wiki/Bitcoind)
7. Install [Nginx with Passenger](https://www.phusionpassenger.com/)
8. Install JavaScript Runtime
9. Install ImageMagick
10. Configure Peatio
### 1. Setup deploy user
Create (if it doesnt exist) deploy user, and assign it to the sudo group:
sudo adduser deploy
sudo usermod -a -G sudo deploy
Re-login as deploy user
### 2. Install Ruby
Install the ruby build dependencies:
```shell
sudo apt-get install git curl zlib1g-dev build-essential \
libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 \
libxml2-dev libxslt1-dev libcurl4-openssl-dev libffi-dev
```
Install [rvm](https://rvm.io):
```shell
gpg --keyserver hkp://keys.gnupg.net \
--recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 \
7D2BAF1CF37B13E2069D6956105BD0E739499BDB
\curl -sSL https://get.rvm.io | bash -s stable --ruby=2.2.8 --gems=rails
```
If you want to skip fetching documentation when installing gems,
do the following:
```shell
echo "gem: --no-ri --no-rdoc" > ~/.gemrc
```
### 3. Install MySQL
sudo apt-get install mysql-server mysql-client libmysqlclient-dev
### 4. Install Redis
Be sure to install the latest stable Redis, as the package in the distro may be a bit old:
sudo apt-add-repository -y ppa:rwky/redis
sudo apt-get update
sudo apt-get install redis-server
### 5. Install RabbitMQ
Please follow instructions here: https://www.rabbitmq.com/install-debian.html
curl http://www.rabbitmq.com/rabbitmq-signing-key-public.asc | sudo apt-key add -
sudo apt-add-repository 'deb http://www.rabbitmq.com/debian/ trusty main'
sudo apt-get update
sudo apt-get install rabbitmq-server
sudo rabbitmq-plugins enable rabbitmq_management
sudo service rabbitmq-server restart
wget http://localhost:15672/cli/rabbitmqadmin
chmod +x rabbitmqadmin
sudo mv rabbitmqadmin /usr/local/sbin
### 6. Install Bitcoind
sudo add-apt-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install bitcoind
**Configure**
mkdir -p ~/.bitcoin
touch ~/.bitcoin/bitcoin.conf
vim ~/.bitcoin/bitcoin.conf
Insert the following lines into the bitcoin.conf, and replce with your username and password.
server=1
daemon=1
# If run on the test network instead of the real bitcoin network
testnet=1
# You must set rpcuser and rpcpassword to secure the JSON-RPC api
# Please make rpcpassword to something secure, `5gKAgrJv8CQr2CGUhjVbBFLSj29HnE6YGXvfykHJzS3k` for example.
# Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)
rpcuser=INVENT_A_UNIQUE_USERNAME
rpcpassword=INVENT_A_UNIQUE_PASSWORD
rpcport=18332
# Notify when receiving coins
walletnotify=/usr/local/sbin/rabbitmqadmin publish routing_key=peatio.deposit.coin payload='{"txid":"%s", "channel_key":"satoshi"}'
**Start bitcoin**
bitcoind
### 7. Installing Nginx & Passenger
Install Phusion's PGP key to verify packages
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7
Add HTTPS support to APT
sudo apt-get install apt-transport-https ca-certificates
Add the passenger repository. Note that this only works for Ubuntu 14.04. For other versions of Ubuntu, you have to add the appropriate repository according to Section 2.3.1 of this [link](https://www.phusionpassenger.com/documentation/Users%20guide%20Nginx.html).
sudo add-apt-repository 'deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main'
sudo apt-get update
Install nginx and passenger
sudo apt-get install nginx-extras passenger
Next, we need to update the Nginx configuration to point Passenger to the version of Ruby that we're using. You'll want to open up /etc/nginx/nginx.conf in your favorite editor,
sudo vim /etc/nginx/nginx.conf
find the following lines, and uncomment them:
include /etc/nginx/passenger.conf;
open the passenger.conf file:
sudo vim /etc/nginx/passenger.conf
update the second line to read:
passenger_ruby /home/deploy/.rbenv/shims/ruby;
### 8. Install JavaScript Runtime
A JavaScript Runtime is needed for Asset Pipeline to work. Any runtime will do but Node.js is recommended.
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install nodejs
### 9. Install ImageMagick
sudo apt-get -y install imagemagick gsfonts
### 10. Setup production environment variable
echo "export RAILS_ENV=production" >> ~/.bashrc
source ~/.bashrc
##### Clone the Source
mkdir -p ~/peatio
git clone https://github.com/rubykube/peatio.git ~/peatio/current
cd peatio/current
Install dependency gems
bundle install --without development test --path vendor/bundle
##### Configure Peatio
**Prepare configure files**
bin/init_config
**Setup bitcoind rpc endpoint**
# replace username:password and port with the one you set in
# username and password should only contain letters and numbers, do not use email as username
# bitcoin.conf in previous step
vim config/currencies.yml
**Config database settings**
vim config/database.yml
# Initialize the database and load the seed data
bundle exec rake db:setup
**Run daemons**
Read how to deal with Peatio daemons at [Peatio daemons](https://github.com/rubykube/peatio/blob/master/docs/peatio/daemons.md).
**SSL Certificate setting**
For security reason, you must setup SSL Certificate for production environment, if your SSL Certificated is been configured, please change the following line at `config/environments/production.rb`
config.force_ssl = true
**Passenger:**
sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /home/deploy/peatio/current/config/nginx.conf /etc/nginx/conf.d/peatio.conf
sudo service nginx restart

View File

@@ -0,0 +1,111 @@
# CoinMarketCap API integration
Peatio has a simple way to integrate with CoinMarketCap<br/>
This doc includes technical documentation needed to formulate/standardize exchange API endpoints.<br/>
Exchanges are expected to minimally support the mandatory endpoints outlined below along with their corresponding mandatory data-points for integration.<br/>
## List of supported API endpoints described here:
1. `api/v2/coinmarketcap/summary` - *Overview of market data for all tickers and all markets*<br/>
**Response example:**
```json
[
{
"trading_pairs": "Identifier of a ticker with delimiter to separate base/quote",
"base_currency": "Symbol/currency code of base currency",
"quote_currency": "Symbol/currency code of base currency",
"last_price": "Last transacted price of base currency based on given quote currency",
"lowest_ask": "Lowest Ask price of base currency based on given quote currency",
"highest_bid": "Highest bid price of base currency based on given quote currency",
"base_volume": "24-hr volume of market pair denoted in BASE currency",
"quote_volume": "24-hr volume of market pair denoted in QUOTE currency",
"price_change_percent_24h": "24-hr % price change of market pair",
"highest_price_24h": "Highest price of base currency based on given quote currency in the last 24-hrs",
"lowest_price_24h": "Lowest price of base currency based on given quote currency in the last 24-hrs"
}
]
```
2. `api/v2/coinmarketcap/assets` - *The assets endpoint is to provide a detailed summary for each available currency*<br/>
**Response example:**
```json
[
{
"CURRENCY_CODE": {
"name": "Full name of cryptocurrency",
"unified_cryptoasset_id": "Unique ID of cryptocurrency assigned by Unified Cryptoasset ID",
"can_withdraw": "Identifies whether withdrawals are enabled or disabled",
"can_deposit": "Identifies whether deposits are enabled or disabled",
"min_withdraw": "Identifies the single minimum withdrawal amount of a cryptocurrency"
}
}
]
```
3. `/api/v2/coinmarketcap/ticker` - *The ticker endpoint is to provide a 24-hour pricing and volume summary for each available market pair available* <br/>
**Response example:**
```json
[
{
"MARKET_NAME": {
"base_id": "The quote pair Unified Cryptoasset ID",
"quote_id": "The base pair Unified Cryptoasset ID",
"last_price": "Last transacted price of base currency based on given quote currency",
"base_volume": "24-hour trading volume denoted in BASE currency",
"quote_volume": "24 hour trading volume denoted in QUOTE currency",
"isFrozen": "Indicates if the market is currently enabled (0) or disabled (1)"
}
}
]
```
4. `/api/v2/coinmarketcap/orderbook/:market_pair` - *The order book endpoint is to provide a complete level 2 order book (arranged by best asks/bids) with full depth returned for a given market pair* <br/>
**Parameters:**<br/>
market_pair - A pair such as “LTC_BTC”\
depth - Orders depth quantity: [0,5,10,20,50,100,500].Not defined or 0 = full order book. Depth = 100 means 50 for each bid/ask side.<br/>
**Response example:**
```javascript
[
{
"timestamp": "Unix timestamp in milliseconds for when the last updated time occurred",
// An array containing 2 elements. The offer price and quantity for each bid order
"bids":[
[
"12462000",
"0.04548320"
],
[
"12457000",
"3.00000000"
]
],
// An array containing 2 elements. The ask price and quantity for each ask order
"asks":[
[
"12506000",
"2.73042000"
],
[
"12508000",
"0.33660000"
]
]
}
]
```
5. `/api/v2/coinmarketcap/trades/:market_pair` - *The trades endpoint is to return data on all recently completed trades for a given market pair* <br/>
**Parameters:**<br/>
market_pair - A pair such as “LTC_BTC”<br/>
**Response example:**
```json
[
{
"trade_id": "A unique ID associated with the trade for the currency pair transaction",
"price": "Last transacted price of base currency based on given quote currency",
"base_volume": "Transaction amount in BASE currency",
"quote_volume": "Transaction amount in QUOTE currency",
"timestamp": "Unix timestamp in milliseconds for when the transaction occurred",
"type": "Used to determine whether or not the transaction originated as a buy or sell"
}
]
```

View File

@@ -0,0 +1,7 @@
# Peatio environments configuration
This document provides description of available configuration through the environment.
### General configuration
| Environment variable | Default value | Possible values | Description |
| ----------------------------- | ------------- | --------------- | ------------------------------------------------------------ |
| `PEATIO_DEPOSIT_FUNDS_LOCKED` | false | `true`, `false` | When turned on (`true`) user funds will be locked on deposit, and unlocked once the collection of this deposit succeed |

42
docs/peatio/daemons.md Normal file
View File

@@ -0,0 +1,42 @@
# Peatio daemons
Peatio daemons are managed by [God](http://godrb.com/).
## Starting daemons
To start God as daemon run:
`god -c lib/daemons/daemons.god`
You can also start God in foreground:
`god -c lib/daemons/daemons.god -D`
**God starts all daemons when it is being initialized.**
Use `god stop` to stop all daemons. God will still be up.
Use `god start` to start all daemons.
## Stopping daemons
To stop God and all daemons run:
`god terminate`
To stop only daemons leaving God up run:
`god stop`
## Restarting daemons
`god restart`
Be patient when starting or stopping daemons: most of daemons support graceful termination so God will first send SIGTERM, wait short period of time, and forcefully kill process by sending SIGKILL if it is still up.
## Querying status
`god status`
## Reading logs
Each daemon has it's own log file localed at `log/daemons`.

View File

@@ -0,0 +1,30 @@
# Peatio deposit flow
## Previous version
In previous version we had deposit collection flow based on amqp daemon (deposit_collection_fees, deposit_collection)
Legacy deposit process diagram:
![image](../images/peatio/legacy_deposits_flow.png)
1. Blockchain daemon process blocks and filter platform deposits.
2. We are waiting for the N number of confirmations.
3. Blockchain daemon produces AMQP message for deposit_collection_fees daemon.
4. deposit_collection_fees daemon trying to collect fees if needed (erc20 case) and after collection immediately produce a message for the next daemon (deposit_collection).
deposit_collection daemon processing message and trying to collect deposit depending on the deposit spread.
The main problem for this approach that we don't wait till the transaction that we generated in the deposit_collection_fees daemon successfully executed and we are failing on deposit collection in the last step (it happens mostly for each erc20 deposit). Also, there is some chance that we can miss amqp message due to server instability.
## New deposit collection flow based on SQL worker
We decided to remove to AMQP base deposit daemons and create a new deposit daemon that will work on deposit states changes and will prevent immediate proceeding of erc20 deposits.
New deposit process diagram:
![image](../images/peatio/new_deposits_flow.png)
1. Blockchain daemon process blocks and filter platform deposits.
2. We are waiting for the N number of confirmations.
3. In the deposit daemons we select each 60s deposits with state `processing` and `fee_processing`.
4. For `processing` deposits we are checking if plugin implement method `prepare_deposit_collection!` if it doesn't we immediately process the deposit and collect deposit to the `hot`, `warm`, `cold` wallets. If plugin implement method `prepare_deposit_collection!` daemon processing of collection fees and change deposit state to `fee_processing`.
For deposits with `fee_processing` state, we select each minute deposits that have `updated_at` older than 5 minutes and process them. With time condition we are sure that fee transaction has already been executed.

45
docs/peatio/engine.md Normal file
View File

@@ -0,0 +1,45 @@
# ENGINES
Engines in Peatio represent market's matching engine settings.
| column | Desc |
| ---------------- | ---------------------------------------------------- |
| id | an unique identifier in database |
| name | human-readable description |
| driver | More about driver in DRIVERS section |
| uid | User's UID for upstream markets (more in UPSTREAM) |
| url | URL for upstream |
| key_encrypted | apikey kid for upstream |
| secret_encrypted | apikey secret for upstream |
| data_encrypted | can hold any engine-specific key-value configuration |
| state | Either online or offline |
Every market belongs to one of defined engines and every engine should have one of supported drivers.
## DRIVERS
Drivers can be divided into two groups - Local or Upstream.
Supported local drivers are peatio and finex-spot.
Peatio comes with peatio driver available only.
Upstream drivers are supported in finex trading engine.
## UPSTREAM
Upstream is a remote platform you can connect to to use them as liquidity provider for your platform.
To setup upstream market, you need to create an upstream engine:
```ruby
engine = Engine.create(name: "BitFinex", driver: "bitfinex", uid: "UID", key: "KID", secret: "SECRET", url: "wss://api.bitfinex.com/ws/2", data: {"rest": "http://api-pub.bitfinex.com/ws/2", "websocket": "wss://api-pub.bitfinex.com/ws/2", "trade_proxy"=>true, "orderbook_proxy"=>true})
```
`UID` is an 'upstream' user UID on **your platform**. When you submit an order to the upstream market and get a trade on remote platform, the trade will be recorded as a trade between you and this user.
`KID` and `SECRET` are your **remote platform** credentials.
`data` field should contain a configuration for trade and orderbook proxy. Peatio Upstream daemon will connect to the remote platform via `rest` and `websocket` params in data and will forward latest trades and incremental orderbook updates to your platform.
And do not forget to deposit some funds to remote platform :)

View File

@@ -0,0 +1,168 @@
## Opendax Wallet plugin
This service is used in OpenDAX Go HDwallet microservice to generate wallets, sign and broadcast transactions. It is using BIP-32 HD Wallet, which mean all addresses are generated from one master seed
### Settings configuration examples
Deposit wallet
```json
blockchain_key: eth blockchain (infura) with right explorer_address, explorer_transaction
gateway: field set as `opendax`
settings:
uri: a link to go-hd microservice (e.g. "https://hdwallet/api/v2/hdwallet")
gateway_url: a url of the infura or private node for broadcast transactions
```
Example:
```ruby
Wallet.create!(
blockchain_key: "eth-testnet",
name: "ETH/ERC-20 Deposit Wallet",
address: "changeme",
gateway: "opendax",
kind: "deposit",
settings: {uri: "https://hdwallet/api/v2/hdwallet", gateway_url: "https://infura.io"},
max_balance: 0,
status: "active"
)
```
Hot wallet
To save Hot wallet you need to generate it [see](#create-address)
```json
blockchain_key: eth blockchain (infura) with right explorer_address, explorer_transaction
gateway: field set as `opendax`
address: Hot wallet address
settings:
uri: a link to go-hd microservice (https://hdwallet/api/v2/hdwallet)
gateway_url: a url of the infura or private node for broadcast transactions
wallet_index: should be vault encrypted secret from wallet private key
secret: index provided in the address generation step
```
Example:
```ruby
Wallet.create!(
blockchain_key: "eth-testnet",
name: "ETH/ERC-20 HOT Wallet",
address: "hot-wallet-address",
gateway: "opendax",
kind: "hot",
settings: {
uri: "https://hdwallet/api/v2/hdwallet",
gateway_url: "https://infura.io"},
wallet_index: 1,
secret: "changeme",
max_balance: 1000,
status: "active"
)
```
#### Implemented functions are
### Create address
To test address creating you need to be sure that:
1. You have deposit wallet with right configuration
- `blockchain_key` should be some fake blockchain with right explorer_address, explorer_transaction
- `gateway` field set as `opendax`
- in wallet settings you have:
- `uri` should be a link to go-hd microservice, default is `https://hdwallet/api/v2/hdwallet`;
- `gateway_url` should be a url of the crypto node, infura;
- `passphrase` - should be vault encrypted secret from wallet private key;
- `wallet_index` - index provided in the address generation step
### There are 3 options to test:
1. From rails console
```ruby
# Find deposit wallet and save it to variable
w = Wallet.find(id)
service = WalletService.new(w)
service.create_address!(uid, {})
# response
{
"address":"0x6876447bF1ab4efc09740e242eaED2Ab389509a4",
"passphrase":"2ee7dc93b6581c3ac31f62d32257477e",
"coin-type":"eth",
"wallet-index":20004
}
```
2. From API call
`api/v2/peatio/account/deposit_address/:currency`
```json
// response
{
"currencies": ["bigo","cro","eth"],
"address":"0xb06dd7f8ee1852cf3f9e43b9a703a06f8e28d31f",
"state":"active"
}
```
3. From peatio daemon
To check if there is some problem, with user address generation you should check `amqp-daemon-deposit-coin-address` daemon logs
To verify address information has right format
```ruby
# Find deposit wallet and member configuration
wallet = Wallet.find(id)
member = Member.find_by(email 'your email')
# Find member payment address
payment_address = PaymentAddress.find_by(wallet_id: wallet.id, member_id: member.id)
# In payment address secret should be information about passphrase (encrypted password from private key)
payment_address.secret
"a4ee099cc541dd222dc24ea546dd46c6"
# In payment address details should be information about wallet index, and coin type
payment_address.details
{"wallet_index"=>2, "coin_type"=>"eth"}
```
### Create transaction
To test create transaction you should have all configuration described on `create_address` step for all wallets related to your currency (especially deposit, hot wallet)
Be sure that you have blockchain configured before doing transaction and this blockchain-key connected both for currency and wallets!
Blockchain `server` param should be the same as `url` param in wallet settings (node url, infura url)
1. Deposit
- Deposit some funds to your created address
- Check logs of `daemon-deposit`
- You can get information about deposit status from rails console, admin tower or your wallet page
2. Withdraw
- Transfer funds from your account
- Check logs of `amqp-daemon-withdraw-coin` about withdraw status from rails console, admin tower or your wallet page
### Load balance
To test load balance you should have all configuration described on `create_address` step for all wallets related to your currency (deposit, hot, warm, cold)
### There are 2 options to test:
1. From rails console
```ruby
1. Find deposit wallet and save it to variable
w = Wallet.find(id)
w.current_balance
# response
{
"balance":216380800000000000
}
```
2. From Admin API call
`api/v2/peatio/admin/wallets/:id`
```json
//response
"id": 1,
"name": "Test wallet",
"kind": "deposit",
"currencies": ["fth","seele"],
"address": "changeme",
"gateway": "parity",
"max_balance": "212.0",
"balance": {
"fth": "2.3",
"seele": "223.3"
},
"blockchain_key": "eth-testnet",
"status": "active",
"created_at": "2020-09-10T17:53:03+02:00","updated_at": "2020-10-20T05:00:49+02:00"
```

View File

@@ -0,0 +1,84 @@
## Trader PnL calculation
This doc describes how you can calculate a traders total P&L
| Term | Definition |
| ------------------ | ------------------------------------------------------------ |
| PnL currency | The currency into which the entries are converted to. |
| Currency | Trader income or outcome currency |
| Total Credit | Sum of incomes of the trader in the currency (without fees) |
| Total Credit Fees | Sum of fees applied to incomes of the trader in the currency |
| Total Credit Value | (Total Credit + Total Credit Fees) estimated in pnl currency using the latest market price |
| Total Debit | Sum of outcomes of the trader in the currency (without fees) |
| Total Debit Fees | Sum of fees applied to outcomes of the trader in the currency |
| Total Debit Value | (Total Debit + Total Debit Fees) estimated in pnl currency |
| Average Buy Price | Total Credit Value / (Total Credit + Total Credit Fees) |
| Average Sell Price | Total Debit Value / (Total Debit + Total Debit Fees) |
### Configuration
To enable the PnL calculation for traders you need to setup at least one destination currency in the PNL_CURRENCIES variable.
| Environment Variable | Example | Description |
| -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| PNL_CURRENCIES | usd,btc | List of pnl currencies |
| CONVERSION_PATHS | usd/krw:_usdt/usd,usdt/krw this will convert usd to krw using the last price of markets usd/usdt (reversed) and usd/krw | By default conversions are made using the direct market (BTC to USD use latest market price of btc/usd). If a direct conversion market is missing you can specify a conversion path setting this variable. Several paths can be defined with semi-colon (;) separation. |
| PNL_EXCLUDE_ROLES | maker,broker | Skip PnL calculation for users with the following roles |
### Formulas
#### Calculate user Realized PNL
##### For one currency
-----
###### Realized PNL Value = Total Debit Value * (Average Sell Price - Average Buy Price) / Average Sell Price
-----
#### Calculate user Unrealized PNL
##### For one currency
-----
###### Asset Current Value = Balance * Last Market Price
###### Asset Average Buy Value = Balance * Average Buy Price
###### Unrealized PNL Value = Asset Current Value - Asset Average Buy Value
###### Unrealized PNL Percentage = (100 * Unrealized PNL Value) / Asset Average Buy Value
-----
#### Calculate user Total PNL
##### For one currency
-----
###### Total PNL = Realized PNL + Unrealized PNL
-----
#### Total user assets PNL
-----
###### Total Asset Average Value = SUM(Asset Average Buy Value)
###### Total Asset Current Value = SUM(Asset Current Value)
###### Total PNL Value = Total Asset Current Value - Total Asset Average Value
###### Total PNL Percentage = (100 * Total PNL Value) / Total Asset Average Value
-----
#### 1) Initial State
|Currency| Balance |Total Credit | Total Credit Fees | Total Credit Value | Total Debit | Total Debit Fees | Total Debit Value | Average Buy Price | Average Sell Price | Realized PNL | Unrealized PNL| Total PNL | Average PNL Price |Total PNL Value|
|---|---|---|---|---|---|---| ---|---|---|---|---|---|---|---|
| BTC | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0| 0| 0| 0| 0 | 0|
#### 2) Deposit 3 BTC, Portfolio Currency = ETH, Last Market Price (BTC/ETH) = 10 000
|Currency| Balance |Total Credit | Total Credit Fees | Total Credit Value | Total Debit | Total Debit Fees | Total Debit Value | Average Buy Price | Average Sell Price | Realized PNL | Unrealized PNL| Total PNL | Average PNL Price |Total PNL Value|
|---|---|---|---|---|---|---| ---|---|---|---|---|---|---|---|
| BTC | 2.994000 | 2.994000 | 0.006000 | 30 000 | 0 | 0 | 0 | 10 000| 0| 0| 0| 0| 10000 | 29940 |
-------
###### Average Buy Price = 30000 / (2.994000 + 0.006000) = 10000
###### Total PNL Value = Total Credit * Average Buy Price -Total Debit Value = 2.994000 * 10 000 - 0 = 29940
###### Average PNL Price = Total PNL Value / Balance = 29940 / 2.994000 = 10000
------
#### 3) Sell 1 BTC, Portfolio Currency = ETH, Last Market Price (BTC/ETH) = 9000
|Currency| Balance |Total Credit | Total Credit Fees | Total Credit Value | Total Debit | Total Debit Fees | Total Debit Value | Average Buy Price | Average Sell Price | Realized PNL | Unrealized PNL| Total PNL | Average PNL Price |Total PNL Value|
|---|---|---|---|---|---|---| ---|---|---|---|---|---|---|---|
| BTC| 1.994000 | 2.994000 | 0.006000| 30 000 | 1 | 0 | 9000 | 10 000 | 9000 | -1000| -1994| -2994 | 10501.5045135 | 20940 |
------
###### Average Sell Price = 9000 / (1 + 0.006000) = 9000
###### Realized PNL = Total Debit Value * (Average Sell Price - Average Buy Price) / Average Sell Price = 9000 * (9000 - 10 000) / 9000 = -1000
###### Unrealized PNL = Balance * Last Market Price (BTC/ETH) - Balance * Average Buy Price = 1.994000 * 9000 - 1.994000 * 10 000 = - 1994
###### Total PNL = Realized PNL + Unrealized PNL = -1000 + (-1994) = -2994
###### Total PNL Value = Total Credit * Average Buy Price - Total Debit Value = 2.994000 * 10 000 - 9000 = 20940
###### Average PNL Price = Total PNL Value / Balance = 20940 / 1.994000 = 10501.5045135
-----

View File

@@ -0,0 +1,33 @@
## Global Withdraw Limits
This document describes how withdraw limits works in opendax peatio.
Withdraw limits schema:
| Term | Definition |
| -------------- | ------------------------------------------------ |
| Group | Member group. Will be used to select limit |
| KYC Level | Member KYC level. Will be used to select limit |
| 24 hour limit | 24 hour limit in platform currency e.g. USD |
| 1 month limit | 1 month limit in platform currency e.g. USD |
Every user has a KyC level (starts from 0) and a group (default is 'any').
The KYC level has a higher priority than group match.
For example a member with kyc_level 2 and group 'vip-0' will match the following rules in order:
The first is the highest priority.
|KYC level|Group |Priority|
|---------|---------|--------|
| 2 | vip-0 | 1 |
| 2 | any | 2 |
| any | vip-0 | 3 |
| any | any | 4 |
Withdraw limits check flow:
1. If the user hasn't reached any withdrawal limits, the system process the withdrawal request automatically from the currency 'Hot wallet'. If the 'Hot wallet' doesn't have enough funds to process the withdrawal request the system will throw an error. In this situation, the admin needs to replenish the 'Hot wallet'.
2. If the user reached at least one of withdrawal limits (24 hours or 1 month) the system accepts the request, locks the user funds but doesn't process the withdraw automatically. Admin can manually reject or process this withdrawal request from the 'Hot wallet' or process it manually from the warm wallet.
More info about [Peatio Financial Flow](https://www.openware.com/sdk/guides/operator/financial-flow.html) and [Peatio Wallet Guidelines](https://www.openware.com/sdk/guides/operator/wallet-guidelines.html).

View File

@@ -0,0 +1,653 @@
# Performance of order creation, matching & trade execution
**Creating orders**
Creating orders is done using:
1. <https://github.com/rubykube/peatio/blob/1-8-stable/app/api/api_v2/orders.rb#L52>
2. <https://github.com/rubykube/peatio/blob/1-8-stable/app/services/ordering.rb#L12>
When we create order the system locks account and subtracts `Account#balance` and increases `Account#locked` (e.g. locks money). The parallel requests must wait until lock will be released.
**Executing trades**
Daemon `Worker::TradeExecutor` receives IDs of two orders which are matched. Then it attempts to modify balances on each account. See https://github.com/rubykube/peatio/blob/1-8-stable/app/trading/matching/executor.rb#L53
The whole code it wrapped into transaction.
Orders are locked at:
- <https://github.com/rubykube/peatio/blob/1-8-stable/app/trading/matching/executor.rb#L57>
Accounts are locked at:
- <https://github.com/rubykube/peatio/blob/1-8-stable/app/trading/matching/executor.rb#L81>
- <https://github.com/rubykube/peatio/blob/1-8-stable/app/trading/matching/executor.rb#L82>
Full text available from: [Performance of order creation, matching & trade execution](https://github.com/rubykube/peatio/issues/1145)
**Benchmark of trading**
Intel i3-8100 four physical cores, 16GB memory, SSD RAID0.
Single instance of each component.
Highly optimized MySQL.
Was used simple Docker deployment, a little modified <https://github.com/rubykube/toolbox#stress-testing-peatio-trading-engine> utility so it creates orders with predictable results and fresh database.
The benchmark must be run in production (Kubernetes deployment) with 5 instances of Rails applications and 5 instances of trade_executor daemons. Other daemons must have 1 instance per each.
For Peatio 1.8.9 + [#1110](https://github.com/rubykube/peatio/pull/1110) on top of it.
**Trading engine benchmark (10000 orders, 10 simultaneous requests, 10 traders)**
Order creation API: 57.51 orders per second (173.88 seconds for 10000 orders).
Order execution: 28.05 deals per second (178.19 seconds in total for 5000 deals).
**Trading engine benchmark (10000 orders, 100 simultaneous requests, 100 traders)**
Order creation API: 62.07 orders per second (161.10 seconds for 10000 orders).
Order execution: 30.83 deals per second (162.15 seconds in total for 5000 deals).
For Peatio 1.8.9 + [#1110](https://github.com/rubykube/peatio/pull/1110), [#1215](https://github.com/rubykube/peatio/pull/1215), [#1193](https://github.com/rubykube/peatio/pull/1193) and on top of patches [#1214](https://github.com/rubykube/peatio/pull/1214).
*5 Rails instances each with 2 threads.*
*One instance per each daemon.*
*Fresh database (no records at all)*
**Average orders per second (creation): (123.08 + 115.54 + 130.98 + 128.71 + 128.91) / 5 = 125.444**
```
Root URL: http://peatio.trade:4000
Currencies: BTC, USD
Markets: BTCUSD
Number of simultaneous traders: 10
Number of orders to create: 1000
Number of simultaneous requests: 10
Minimum order volume: 1.0
Maximum order volume: 100.0
Order volume step: 1.0
Minimum order price: 0.5
Maximum order price: 1.5
Order price step: 0.1
Creating 10 traders... OK
Making each trader billionaire... OK
10 of 1000 orders created (0.11 seconds passed).
20 of 1000 orders created (0.2 seconds passed).
30 of 1000 orders created (0.27 seconds passed).
40 of 1000 orders created (0.35 seconds passed).
50 of 1000 orders created (0.43 seconds passed).
60 of 1000 orders created (0.5 seconds passed).
70 of 1000 orders created (0.57 seconds passed).
80 of 1000 orders created (0.65 seconds passed).
90 of 1000 orders created (0.72 seconds passed).
100 of 1000 orders created (0.8 seconds passed).
110 of 1000 orders created (0.86 seconds passed).
120 of 1000 orders created (0.93 seconds passed).
130 of 1000 orders created (1.02 seconds passed).
140 of 1000 orders created (1.1 seconds passed).
150 of 1000 orders created (1.17 seconds passed).
160 of 1000 orders created (1.26 seconds passed).
170 of 1000 orders created (1.33 seconds passed).
180 of 1000 orders created (1.4 seconds passed).
190 of 1000 orders created (1.47 seconds passed).
200 of 1000 orders created (1.55 seconds passed).
210 of 1000 orders created (1.63 seconds passed).
220 of 1000 orders created (1.71 seconds passed).
230 of 1000 orders created (1.79 seconds passed).
240 of 1000 orders created (1.87 seconds passed).
250 of 1000 orders created (1.94 seconds passed).
260 of 1000 orders created (2.01 seconds passed).
270 of 1000 orders created (2.09 seconds passed).
280 of 1000 orders created (2.17 seconds passed).
290 of 1000 orders created (2.24 seconds passed).
300 of 1000 orders created (2.32 seconds passed).
310 of 1000 orders created (2.39 seconds passed).
320 of 1000 orders created (2.47 seconds passed).
330 of 1000 orders created (2.56 seconds passed).
340 of 1000 orders created (2.65 seconds passed).
350 of 1000 orders created (2.71 seconds passed).
360 of 1000 orders created (2.79 seconds passed).
370 of 1000 orders created (2.87 seconds passed).
380 of 1000 orders created (2.94 seconds passed).
390 of 1000 orders created (3.02 seconds passed).
400 of 1000 orders created (3.1 seconds passed).
410 of 1000 orders created (3.17 seconds passed).
420 of 1000 orders created (3.65 seconds passed).
430 of 1000 orders created (3.74 seconds passed).
440 of 1000 orders created (3.81 seconds passed).
450 of 1000 orders created (3.89 seconds passed).
460 of 1000 orders created (3.96 seconds passed).
470 of 1000 orders created (4.04 seconds passed).
480 of 1000 orders created (4.12 seconds passed).
490 of 1000 orders created (4.19 seconds passed).
500 of 1000 orders created (4.27 seconds passed).
510 of 1000 orders created (4.34 seconds passed).
520 of 1000 orders created (4.41 seconds passed).
530 of 1000 orders created (4.49 seconds passed).
540 of 1000 orders created (4.56 seconds passed).
550 of 1000 orders created (4.63 seconds passed).
560 of 1000 orders created (4.72 seconds passed).
570 of 1000 orders created (4.81 seconds passed).
580 of 1000 orders created (4.89 seconds passed).
590 of 1000 orders created (4.97 seconds passed).
600 of 1000 orders created (5.05 seconds passed).
610 of 1000 orders created (5.12 seconds passed).
620 of 1000 orders created (5.2 seconds passed).
630 of 1000 orders created (5.28 seconds passed).
640 of 1000 orders created (5.36 seconds passed).
650 of 1000 orders created (5.45 seconds passed).
660 of 1000 orders created (5.51 seconds passed).
670 of 1000 orders created (5.59 seconds passed).
680 of 1000 orders created (5.66 seconds passed).
690 of 1000 orders created (5.74 seconds passed).
700 of 1000 orders created (5.82 seconds passed).
710 of 1000 orders created (5.9 seconds passed).
720 of 1000 orders created (5.99 seconds passed).
730 of 1000 orders created (6.04 seconds passed).
740 of 1000 orders created (6.12 seconds passed).
750 of 1000 orders created (6.19 seconds passed).
760 of 1000 orders created (6.27 seconds passed).
770 of 1000 orders created (6.34 seconds passed).
780 of 1000 orders created (6.43 seconds passed).
790 of 1000 orders created (6.5 seconds passed).
800 of 1000 orders created (6.58 seconds passed).
810 of 1000 orders created (6.65 seconds passed).
820 of 1000 orders created (6.73 seconds passed).
830 of 1000 orders created (6.81 seconds passed).
840 of 1000 orders created (6.89 seconds passed).
850 of 1000 orders created (6.96 seconds passed).
860 of 1000 orders created (7.04 seconds passed).
870 of 1000 orders created (7.11 seconds passed).
880 of 1000 orders created (7.18 seconds passed).
890 of 1000 orders created (7.27 seconds passed).
900 of 1000 orders created (7.36 seconds passed).
910 of 1000 orders created (7.43 seconds passed).
920 of 1000 orders created (7.5 seconds passed).
930 of 1000 orders created (7.58 seconds passed).
940 of 1000 orders created (7.64 seconds passed).
950 of 1000 orders created (7.73 seconds passed).
960 of 1000 orders created (7.81 seconds passed).
970 of 1000 orders created (7.88 seconds passed).
980 of 1000 orders created (7.97 seconds passed).
990 of 1000 orders created (8.06 seconds passed).
1000 of 1000 orders created (8.13 seconds passed).
123.08 orders per second.
```
```
Root URL: http://peatio.trade:4000
Currencies: BTC, USD
Markets: BTCUSD
Number of simultaneous traders: 10
Number of orders to create: 1000
Number of simultaneous requests: 10
Minimum order volume: 1.0
Maximum order volume: 100.0
Order volume step: 1.0
Minimum order price: 0.5
Maximum order price: 1.5
Order price step: 0.1
Creating 10 traders... OK
Making each trader billionaire... OK
10 of 1000 orders created (0.1 seconds passed).
20 of 1000 orders created (0.19 seconds passed).
30 of 1000 orders created (0.27 seconds passed).
40 of 1000 orders created (0.33 seconds passed).
50 of 1000 orders created (0.42 seconds passed).
60 of 1000 orders created (0.49 seconds passed).
70 of 1000 orders created (0.57 seconds passed).
80 of 1000 orders created (0.64 seconds passed).
90 of 1000 orders created (0.72 seconds passed).
100 of 1000 orders created (0.81 seconds passed).
110 of 1000 orders created (0.88 seconds passed).
120 of 1000 orders created (0.96 seconds passed).
130 of 1000 orders created (1.03 seconds passed).
140 of 1000 orders created (1.1 seconds passed).
150 of 1000 orders created (1.19 seconds passed).
160 of 1000 orders created (1.28 seconds passed).
170 of 1000 orders created (1.37 seconds passed).
180 of 1000 orders created (1.45 seconds passed).
190 of 1000 orders created (1.52 seconds passed).
200 of 1000 orders created (1.6 seconds passed).
210 of 1000 orders created (1.69 seconds passed).
220 of 1000 orders created (1.74 seconds passed).
230 of 1000 orders created (1.81 seconds passed).
240 of 1000 orders created (1.88 seconds passed).
250 of 1000 orders created (1.96 seconds passed).
260 of 1000 orders created (2.04 seconds passed).
270 of 1000 orders created (2.1 seconds passed).
280 of 1000 orders created (2.19 seconds passed).
290 of 1000 orders created (2.25 seconds passed).
300 of 1000 orders created (2.81 seconds passed).
310 of 1000 orders created (2.94 seconds passed).
320 of 1000 orders created (3.0 seconds passed).
330 of 1000 orders created (3.07 seconds passed).
340 of 1000 orders created (3.16 seconds passed).
350 of 1000 orders created (3.24 seconds passed).
360 of 1000 orders created (3.32 seconds passed).
370 of 1000 orders created (3.39 seconds passed).
380 of 1000 orders created (3.46 seconds passed).
390 of 1000 orders created (3.53 seconds passed).
400 of 1000 orders created (3.6 seconds passed).
410 of 1000 orders created (3.67 seconds passed).
420 of 1000 orders created (3.76 seconds passed).
430 of 1000 orders created (3.84 seconds passed).
440 of 1000 orders created (3.9 seconds passed).
450 of 1000 orders created (3.99 seconds passed).
460 of 1000 orders created (4.08 seconds passed).
470 of 1000 orders created (4.15 seconds passed).
480 of 1000 orders created (4.24 seconds passed).
490 of 1000 orders created (4.32 seconds passed).
500 of 1000 orders created (4.39 seconds passed).
510 of 1000 orders created (4.47 seconds passed).
520 of 1000 orders created (4.54 seconds passed).
530 of 1000 orders created (4.6 seconds passed).
540 of 1000 orders created (4.68 seconds passed).
550 of 1000 orders created (4.76 seconds passed).
560 of 1000 orders created (4.82 seconds passed).
570 of 1000 orders created (4.9 seconds passed).
580 of 1000 orders created (4.96 seconds passed).
590 of 1000 orders created (5.05 seconds passed).
600 of 1000 orders created (5.12 seconds passed).
610 of 1000 orders created (5.2 seconds passed).
620 of 1000 orders created (5.28 seconds passed).
630 of 1000 orders created (5.36 seconds passed).
640 of 1000 orders created (5.44 seconds passed).
650 of 1000 orders created (5.51 seconds passed).
660 of 1000 orders created (5.58 seconds passed).
670 of 1000 orders created (5.67 seconds passed).
680 of 1000 orders created (5.75 seconds passed).
690 of 1000 orders created (5.82 seconds passed).
700 of 1000 orders created (5.89 seconds passed).
710 of 1000 orders created (5.96 seconds passed).
720 of 1000 orders created (6.03 seconds passed).
730 of 1000 orders created (6.1 seconds passed).
740 of 1000 orders created (6.18 seconds passed).
750 of 1000 orders created (6.26 seconds passed).
760 of 1000 orders created (6.33 seconds passed).
770 of 1000 orders created (6.4 seconds passed).
780 of 1000 orders created (6.47 seconds passed).
790 of 1000 orders created (6.55 seconds passed).
800 of 1000 orders created (6.62 seconds passed).
810 of 1000 orders created (6.7 seconds passed).
820 of 1000 orders created (6.78 seconds passed).
830 of 1000 orders created (6.85 seconds passed).
840 of 1000 orders created (6.93 seconds passed).
850 of 1000 orders created (7.0 seconds passed).
860 of 1000 orders created (7.08 seconds passed).
870 of 1000 orders created (7.15 seconds passed).
880 of 1000 orders created (7.25 seconds passed).
890 of 1000 orders created (7.56 seconds passed).
900 of 1000 orders created (7.9 seconds passed).
910 of 1000 orders created (7.98 seconds passed).
920 of 1000 orders created (8.06 seconds passed).
930 of 1000 orders created (8.12 seconds passed).
940 of 1000 orders created (8.19 seconds passed).
950 of 1000 orders created (8.25 seconds passed).
960 of 1000 orders created (8.34 seconds passed).
970 of 1000 orders created (8.42 seconds passed).
980 of 1000 orders created (8.49 seconds passed).
990 of 1000 orders created (8.57 seconds passed).
1000 of 1000 orders created (8.67 seconds passed).
115.54 orders per second.
```
```
Root URL: http://peatio.trade:4000
Currencies: BTC, USD
Markets: BTCUSD
Number of simultaneous traders: 10
Number of orders to create: 1000
Number of simultaneous requests: 10
Minimum order volume: 1.0
Maximum order volume: 100.0
Order volume step: 1.0
Minimum order price: 0.5
Maximum order price: 1.5
Order price step: 0.1
Creating 10 traders... OK
Making each trader billionaire... OK
10 of 1000 orders created (0.1 seconds passed).
20 of 1000 orders created (0.19 seconds passed).
30 of 1000 orders created (0.25 seconds passed).
40 of 1000 orders created (0.33 seconds passed).
50 of 1000 orders created (0.39 seconds passed).
60 of 1000 orders created (0.46 seconds passed).
70 of 1000 orders created (0.53 seconds passed).
80 of 1000 orders created (0.61 seconds passed).
90 of 1000 orders created (0.68 seconds passed).
100 of 1000 orders created (0.75 seconds passed).
110 of 1000 orders created (0.83 seconds passed).
120 of 1000 orders created (0.9 seconds passed).
130 of 1000 orders created (0.96 seconds passed).
140 of 1000 orders created (1.03 seconds passed).
150 of 1000 orders created (1.12 seconds passed).
160 of 1000 orders created (1.19 seconds passed).
170 of 1000 orders created (1.25 seconds passed).
180 of 1000 orders created (1.32 seconds passed).
190 of 1000 orders created (1.4 seconds passed).
200 of 1000 orders created (1.49 seconds passed).
210 of 1000 orders created (1.56 seconds passed).
220 of 1000 orders created (1.63 seconds passed).
230 of 1000 orders created (1.71 seconds passed).
240 of 1000 orders created (1.78 seconds passed).
250 of 1000 orders created (1.85 seconds passed).
260 of 1000 orders created (1.93 seconds passed).
270 of 1000 orders created (1.99 seconds passed).
280 of 1000 orders created (2.06 seconds passed).
290 of 1000 orders created (2.14 seconds passed).
300 of 1000 orders created (2.21 seconds passed).
310 of 1000 orders created (2.3 seconds passed).
320 of 1000 orders created (2.37 seconds passed).
330 of 1000 orders created (2.44 seconds passed).
340 of 1000 orders created (2.53 seconds passed).
350 of 1000 orders created (2.61 seconds passed).
360 of 1000 orders created (2.67 seconds passed).
370 of 1000 orders created (2.73 seconds passed).
380 of 1000 orders created (2.81 seconds passed).
390 of 1000 orders created (2.88 seconds passed).
400 of 1000 orders created (2.97 seconds passed).
410 of 1000 orders created (3.05 seconds passed).
420 of 1000 orders created (3.13 seconds passed).
430 of 1000 orders created (3.2 seconds passed).
440 of 1000 orders created (3.27 seconds passed).
450 of 1000 orders created (3.34 seconds passed).
460 of 1000 orders created (3.41 seconds passed).
470 of 1000 orders created (3.49 seconds passed).
480 of 1000 orders created (3.56 seconds passed).
490 of 1000 orders created (3.63 seconds passed).
500 of 1000 orders created (3.71 seconds passed).
510 of 1000 orders created (3.78 seconds passed).
520 of 1000 orders created (3.86 seconds passed).
530 of 1000 orders created (3.94 seconds passed).
540 of 1000 orders created (4.02 seconds passed).
550 of 1000 orders created (4.09 seconds passed).
560 of 1000 orders created (4.16 seconds passed).
570 of 1000 orders created (4.25 seconds passed).
580 of 1000 orders created (4.32 seconds passed).
590 of 1000 orders created (4.39 seconds passed).
600 of 1000 orders created (4.45 seconds passed).
610 of 1000 orders created (4.51 seconds passed).
620 of 1000 orders created (4.59 seconds passed).
630 of 1000 orders created (4.67 seconds passed).
640 of 1000 orders created (4.74 seconds passed).
650 of 1000 orders created (4.82 seconds passed).
660 of 1000 orders created (4.9 seconds passed).
670 of 1000 orders created (4.97 seconds passed).
680 of 1000 orders created (5.05 seconds passed).
690 of 1000 orders created (5.13 seconds passed).
700 of 1000 orders created (5.2 seconds passed).
710 of 1000 orders created (5.28 seconds passed).
720 of 1000 orders created (5.37 seconds passed).
730 of 1000 orders created (5.44 seconds passed).
740 of 1000 orders created (5.51 seconds passed).
750 of 1000 orders created (5.59 seconds passed).
760 of 1000 orders created (5.66 seconds passed).
770 of 1000 orders created (5.74 seconds passed).
780 of 1000 orders created (5.81 seconds passed).
790 of 1000 orders created (5.89 seconds passed).
800 of 1000 orders created (5.97 seconds passed).
810 of 1000 orders created (6.03 seconds passed).
820 of 1000 orders created (6.13 seconds passed).
830 of 1000 orders created (6.18 seconds passed).
840 of 1000 orders created (6.25 seconds passed).
850 of 1000 orders created (6.49 seconds passed).
860 of 1000 orders created (6.58 seconds passed).
870 of 1000 orders created (6.65 seconds passed).
880 of 1000 orders created (6.73 seconds passed).
890 of 1000 orders created (6.8 seconds passed).
900 of 1000 orders created (6.87 seconds passed).
910 of 1000 orders created (6.95 seconds passed).
920 of 1000 orders created (7.03 seconds passed).
930 of 1000 orders created (7.1 seconds passed).
940 of 1000 orders created (7.17 seconds passed).
950 of 1000 orders created (7.27 seconds passed).
960 of 1000 orders created (7.35 seconds passed).
970 of 1000 orders created (7.43 seconds passed).
980 of 1000 orders created (7.49 seconds passed).
990 of 1000 orders created (7.58 seconds passed).
1000 of 1000 orders created (7.66 seconds passed).
130.98 orders per second.
```
```
Root URL: http://peatio.trade:4000
Currencies: BTC, USD
Markets: BTCUSD
Number of simultaneous traders: 10
Number of orders to create: 1000
Number of simultaneous requests: 10
Minimum order volume: 1.0
Maximum order volume: 100.0
Order volume step: 1.0
Minimum order price: 0.5
Maximum order price: 1.5
Order price step: 0.1
Creating 10 traders... OK
Making each trader billionaire... OK
10 of 1000 orders created (0.17 seconds passed).
20 of 1000 orders created (0.25 seconds passed).
30 of 1000 orders created (0.33 seconds passed).
40 of 1000 orders created (0.4 seconds passed).
50 of 1000 orders created (0.46 seconds passed).
60 of 1000 orders created (0.56 seconds passed).
70 of 1000 orders created (0.63 seconds passed).
80 of 1000 orders created (0.71 seconds passed).
90 of 1000 orders created (0.78 seconds passed).
100 of 1000 orders created (0.86 seconds passed).
110 of 1000 orders created (0.95 seconds passed).
120 of 1000 orders created (1.03 seconds passed).
130 of 1000 orders created (1.14 seconds passed).
140 of 1000 orders created (1.23 seconds passed).
150 of 1000 orders created (1.3 seconds passed).
160 of 1000 orders created (1.39 seconds passed).
170 of 1000 orders created (1.46 seconds passed).
180 of 1000 orders created (1.53 seconds passed).
190 of 1000 orders created (1.61 seconds passed).
200 of 1000 orders created (1.68 seconds passed).
210 of 1000 orders created (1.75 seconds passed).
220 of 1000 orders created (1.82 seconds passed).
230 of 1000 orders created (1.91 seconds passed).
240 of 1000 orders created (1.99 seconds passed).
250 of 1000 orders created (2.06 seconds passed).
260 of 1000 orders created (2.13 seconds passed).
270 of 1000 orders created (2.2 seconds passed).
280 of 1000 orders created (2.29 seconds passed).
290 of 1000 orders created (2.37 seconds passed).
300 of 1000 orders created (2.43 seconds passed).
310 of 1000 orders created (2.52 seconds passed).
320 of 1000 orders created (2.59 seconds passed).
330 of 1000 orders created (2.68 seconds passed).
340 of 1000 orders created (2.73 seconds passed).
350 of 1000 orders created (2.81 seconds passed).
360 of 1000 orders created (2.89 seconds passed).
370 of 1000 orders created (2.97 seconds passed).
380 of 1000 orders created (3.05 seconds passed).
390 of 1000 orders created (3.13 seconds passed).
400 of 1000 orders created (3.21 seconds passed).
410 of 1000 orders created (3.28 seconds passed).
420 of 1000 orders created (3.36 seconds passed).
430 of 1000 orders created (3.44 seconds passed).
440 of 1000 orders created (3.51 seconds passed).
450 of 1000 orders created (3.59 seconds passed).
460 of 1000 orders created (3.69 seconds passed).
470 of 1000 orders created (3.75 seconds passed).
480 of 1000 orders created (3.84 seconds passed).
490 of 1000 orders created (3.91 seconds passed).
500 of 1000 orders created (3.98 seconds passed).
510 of 1000 orders created (4.06 seconds passed).
520 of 1000 orders created (4.15 seconds passed).
530 of 1000 orders created (4.23 seconds passed).
540 of 1000 orders created (4.31 seconds passed).
550 of 1000 orders created (4.37 seconds passed).
560 of 1000 orders created (4.45 seconds passed).
570 of 1000 orders created (4.54 seconds passed).
580 of 1000 orders created (4.63 seconds passed).
590 of 1000 orders created (4.7 seconds passed).
600 of 1000 orders created (4.77 seconds passed).
610 of 1000 orders created (4.84 seconds passed).
620 of 1000 orders created (4.91 seconds passed).
630 of 1000 orders created (4.98 seconds passed).
640 of 1000 orders created (5.06 seconds passed).
650 of 1000 orders created (5.15 seconds passed).
660 of 1000 orders created (5.22 seconds passed).
670 of 1000 orders created (5.3 seconds passed).
680 of 1000 orders created (5.38 seconds passed).
690 of 1000 orders created (5.44 seconds passed).
700 of 1000 orders created (5.53 seconds passed).
710 of 1000 orders created (5.59 seconds passed).
720 of 1000 orders created (5.67 seconds passed).
730 of 1000 orders created (5.75 seconds passed).
740 of 1000 orders created (5.81 seconds passed).
750 of 1000 orders created (5.89 seconds passed).
760 of 1000 orders created (5.97 seconds passed).
770 of 1000 orders created (6.03 seconds passed).
780 of 1000 orders created (6.11 seconds passed).
790 of 1000 orders created (6.19 seconds passed).
800 of 1000 orders created (6.27 seconds passed).
810 of 1000 orders created (6.36 seconds passed).
820 of 1000 orders created (6.43 seconds passed).
830 of 1000 orders created (6.51 seconds passed).
840 of 1000 orders created (6.59 seconds passed).
850 of 1000 orders created (6.66 seconds passed).
860 of 1000 orders created (6.72 seconds passed).
870 of 1000 orders created (6.8 seconds passed).
880 of 1000 orders created (6.87 seconds passed).
890 of 1000 orders created (6.95 seconds passed).
900 of 1000 orders created (7.03 seconds passed).
910 of 1000 orders created (7.11 seconds passed).
920 of 1000 orders created (7.19 seconds passed).
930 of 1000 orders created (7.27 seconds passed).
940 of 1000 orders created (7.33 seconds passed).
950 of 1000 orders created (7.4 seconds passed).
960 of 1000 orders created (7.48 seconds passed).
970 of 1000 orders created (7.57 seconds passed).
980 of 1000 orders created (7.63 seconds passed).
990 of 1000 orders created (7.7 seconds passed).
1000 of 1000 orders created (7.77 seconds passed).
128.71 orders per second.
```
```
Root URL: http://peatio.trade:4000
Currencies: BTC, USD
Markets: BTCUSD
Number of simultaneous traders: 10
Number of orders to create: 1000
Number of simultaneous requests: 10
Minimum order volume: 1.0
Maximum order volume: 100.0
Order volume step: 1.0
Minimum order price: 0.5
Maximum order price: 1.5
Order price step: 0.1
Creating 10 traders... OK
Making each trader billionaire... OK
10 of 1000 orders created (0.13 seconds passed).
20 of 1000 orders created (0.19 seconds passed).
30 of 1000 orders created (0.27 seconds passed).
40 of 1000 orders created (0.37 seconds passed).
50 of 1000 orders created (0.46 seconds passed).
60 of 1000 orders created (0.53 seconds passed).
70 of 1000 orders created (0.61 seconds passed).
80 of 1000 orders created (0.67 seconds passed).
90 of 1000 orders created (0.76 seconds passed).
100 of 1000 orders created (0.83 seconds passed).
110 of 1000 orders created (0.91 seconds passed).
120 of 1000 orders created (0.99 seconds passed).
130 of 1000 orders created (1.06 seconds passed).
140 of 1000 orders created (1.13 seconds passed).
150 of 1000 orders created (1.21 seconds passed).
160 of 1000 orders created (1.27 seconds passed).
170 of 1000 orders created (1.36 seconds passed).
180 of 1000 orders created (1.43 seconds passed).
190 of 1000 orders created (1.51 seconds passed).
200 of 1000 orders created (1.57 seconds passed).
210 of 1000 orders created (1.64 seconds passed).
220 of 1000 orders created (1.73 seconds passed).
230 of 1000 orders created (1.81 seconds passed).
240 of 1000 orders created (1.86 seconds passed).
250 of 1000 orders created (1.93 seconds passed).
260 of 1000 orders created (2.02 seconds passed).
270 of 1000 orders created (2.09 seconds passed).
280 of 1000 orders created (2.17 seconds passed).
290 of 1000 orders created (2.26 seconds passed).
300 of 1000 orders created (2.32 seconds passed).
310 of 1000 orders created (2.41 seconds passed).
320 of 1000 orders created (2.48 seconds passed).
330 of 1000 orders created (2.55 seconds passed).
340 of 1000 orders created (2.61 seconds passed).
350 of 1000 orders created (2.7 seconds passed).
360 of 1000 orders created (2.78 seconds passed).
370 of 1000 orders created (2.88 seconds passed).
380 of 1000 orders created (2.95 seconds passed).
390 of 1000 orders created (3.03 seconds passed).
400 of 1000 orders created (3.11 seconds passed).
410 of 1000 orders created (3.18 seconds passed).
420 of 1000 orders created (3.26 seconds passed).
430 of 1000 orders created (3.34 seconds passed).
440 of 1000 orders created (3.42 seconds passed).
450 of 1000 orders created (3.5 seconds passed).
460 of 1000 orders created (3.6 seconds passed).
470 of 1000 orders created (3.67 seconds passed).
480 of 1000 orders created (3.75 seconds passed).
490 of 1000 orders created (3.82 seconds passed).
500 of 1000 orders created (3.91 seconds passed).
510 of 1000 orders created (3.98 seconds passed).
520 of 1000 orders created (4.06 seconds passed).
530 of 1000 orders created (4.15 seconds passed).
540 of 1000 orders created (4.22 seconds passed).
550 of 1000 orders created (4.29 seconds passed).
560 of 1000 orders created (4.36 seconds passed).
570 of 1000 orders created (4.43 seconds passed).
580 of 1000 orders created (4.51 seconds passed).
590 of 1000 orders created (4.59 seconds passed).
600 of 1000 orders created (4.67 seconds passed).
610 of 1000 orders created (4.75 seconds passed).
620 of 1000 orders created (4.83 seconds passed).
630 of 1000 orders created (4.9 seconds passed).
640 of 1000 orders created (4.97 seconds passed).
650 of 1000 orders created (5.06 seconds passed).
660 of 1000 orders created (5.14 seconds passed).
670 of 1000 orders created (5.2 seconds passed).
680 of 1000 orders created (5.28 seconds passed).
690 of 1000 orders created (5.36 seconds passed).
700 of 1000 orders created (5.42 seconds passed).
710 of 1000 orders created (5.51 seconds passed).
720 of 1000 orders created (5.58 seconds passed).
730 of 1000 orders created (5.67 seconds passed).
740 of 1000 orders created (5.74 seconds passed).
750 of 1000 orders created (5.81 seconds passed).
760 of 1000 orders created (5.89 seconds passed).
770 of 1000 orders created (5.98 seconds passed).
780 of 1000 orders created (6.04 seconds passed).
790 of 1000 orders created (6.11 seconds passed).
800 of 1000 orders created (6.22 seconds passed).
810 of 1000 orders created (6.28 seconds passed).
820 of 1000 orders created (6.37 seconds passed).
830 of 1000 orders created (6.45 seconds passed).
840 of 1000 orders created (6.53 seconds passed).
850 of 1000 orders created (6.59 seconds passed).
860 of 1000 orders created (6.68 seconds passed).
870 of 1000 orders created (6.76 seconds passed).
880 of 1000 orders created (6.85 seconds passed).
890 of 1000 orders created (6.93 seconds passed).
900 of 1000 orders created (6.99 seconds passed).
910 of 1000 orders created (7.07 seconds passed).
920 of 1000 orders created (7.15 seconds passed).
930 of 1000 orders created (7.23 seconds passed).
940 of 1000 orders created (7.31 seconds passed).
950 of 1000 orders created (7.38 seconds passed).
960 of 1000 orders created (7.46 seconds passed).
970 of 1000 orders created (7.54 seconds passed).
980 of 1000 orders created (7.62 seconds passed).
990 of 1000 orders created (7.69 seconds passed).
1000 of 1000 orders created (7.77 seconds passed).
128.91 orders per second.
```

35
docs/plugins.md Normal file
View File

@@ -0,0 +1,35 @@
# Peatio Plugin API v2
Peatio plugins v2 is updated peatio plugin system. We distribute plugins as peatio gems.
## Development
1. List your plugins in Gemfile.plugins.
2. Install plugins `bundle install`.
3. Start your plugin development and integration.
## Build
### Using default Dockerfile
Default Dockerfile has two stages. First stage is base image build and second is installation plugins into base image.
Note that building image from scratch takes much more time. If you didn't changes in Peatio code use [Dockerfile.plugin](#using-dockerfileplugin).
* To build base image run `docker build --target base --tag peatio:base .`
* To build image with plugins from scratch run `docker build --tag peatio:custom .`
### Using Dockerfile.plugin
You can use built base image and extend it by adding plugins into `Gemfile.plugin`.
1. Copy `Dockerfile.plugin` and `Gemfile.plugin` into empty directory.
2. List yor plugins in `Gemfile.plugin`.
3. Change base image in `Dockerfile.plugin` (default is rubykube/peatio:latest).
4. Build your custom image `docker build --tag peatio:custom -f Dockerfile.plugin .`

98
docs/releases/1.2.0.md Normal file
View File

@@ -0,0 +1,98 @@
## Peatio 1.2.0 (February 26, 2018) ##
### Overview ###
The release is focused on adding support for Ethereum currency including ability to attach it either to BitGo, either to Geth.
This release is also the first one which is driven by automatic patch number version bumping from TravisCI builds.
We have also fixed all incompatible queries so Peatio is now friendly with MSSQL.
As for bugfixes the release includes lot of UI polishing like missing useful information in admin panel, or UI issues.
### Breaking changes ###
* [#535](https://github.com/rubykube/peatio/pull/535): Remove name & nickname from member & authentication models.
The patch removes name and nickname attributes from `Member` & `Authentication`. We believe this makes Peatio more friendly with OAuth protocol and improves user privacy.
* [#596](https://github.com/rubykube/peatio/pull/596): Remove ability to generate another deposit address.
This patch is a fix for BIP32 incompatible currencies like XRP and ETH.
The bug reproduction steps look like:
1. Generate new address for currency. Let the address you receive be called X.
2. Deposit 10 coins to X.
3. Make withdraw for 2 coins. It will succeed. You now have 8 coins left.
4. Generate another address for the same currency. Let the address be called Y.
5. Request withdraw for 2 coins. It will fail.
The reason second withdraw fails is because Peatio tries to withdraw from the newest deposit address (Y) but it doesn't contain enough funds to proceed the transaction. However, it works well for BIP32 compatible currencies, like Bitcoin.
The patch modifies code to be sure used has only single address per currency.
### New features ###
* [#495](https://github.com/rubykube/peatio/pull/495): Add support for ETH using BitGo.
The patch adds typical required views, routes, controllers, and models for ETH. It also provides ETH configuration skeleton for BitGo.
* [#567](https://github.com/rubykube/peatio/pull/567): Add support for MSSQL.
The patch fixes all MSSQL incompatible queries.
* [#569](https://github.com/rubykube/peatio/pull/569): Add support for ETH using Geth.
The patch adds support for Geth.
It also adds new helper for converting base unit to smallest (like Bitcoins to satoshis): `CoinAPI#convert_to_base_unit!(value)`. The helper ensures your value doesn't exceed maximum allowed precision.
* [#534](https://github.com/rubykube/peatio/pull/534): Add ability to disable cabinet or markets UI by setting environment variables.
Administrators will still have access.
### Enhancements ###
* [#551](https://github.com/rubykube/peatio/pull/551): Output member serial number in admin panel.
The patch outputs member SN in admin panel and allows to search by it through all members.
* [#590](https://github.com/rubykube/peatio/pull/590): Display deposits & withdraws with no limits.
Previously system displayed only last 3 items. Now it displays the whole list.
* [#597](https://github.com/rubykube/peatio/pull/597): Remove obsolete Rails generators for deposits, withdraws, locales, and other stuff.
* [#598](https://github.com/rubykube/peatio/pull/598): Remove unneeded translations for banks, banks configuration files, and helpers.
All these are leftovers after stripping banks.yml.
### Fixes ###
* [#575](https://github.com/rubykube/peatio/pull/575), [#570](https://github.com/rubykube/peatio/pull/570), [#574](https://github.com/rubykube/peatio/pull/574): Documentation fixes.
* [#576](https://github.com/rubykube/peatio/pull/576): Fixes for several reported UI issues at profile & markets pages.
* [#589](https://github.com/rubykube/peatio/pull/589): Page is now reloaded only after successful creation of withdraw.
Previously page was reloaded every time you click `Submit` no matter what data you entered. This prevented users from getting validation errors.
* [#595](https://github.com/rubykube/peatio/pull/595): Fix exception at admin panel when navigating to specific withdraw.
The issues was related to missing call to `find_withdraw` however it was declared as `before_action` hook in base controller class. This is a Rails bug.
* [#585](https://github.com/rubykube/peatio/pull/585): Fix UI issues at «Solvency» page.
Now navigation tabs are displayed in multiple lines so they don't get out of screen.
* [#593](https://github.com/rubykube/peatio/pull/593): Fix UI issue with all confirmation dialogs.
Backdrop is duplicated when pushing enter key multiple times.
* [#582](https://github.com/rubykube/peatio/pull/582): Fix UI issue with user cabinet navigation dropdown.
The patch adds styles which handle short email addresses displayed in dropdown.
## Peatio 1.1.13 and before ##
Unfortunately, release notes are not available for 1.1.13 and below but you still can check [CHANGELOG](https://github.com/rubykube/peatio/blob/master/CHANGELOG.md).

106
docs/releases/1.3.0.md Normal file
View File

@@ -0,0 +1,106 @@
## Peatio 1.3.0 (March 5, 2018) ##
### Overview ###
The release is focused on:
1. Migrating currencies config (config/currencies.yml) to database.
2. Adding support for Rippled.
3. Adding support for PostgreSQL.
### Breaking changes ###
* [#488](https://github.com/rubykube/peatio/pull/488): Move currencies.yml to database.
Migration steps (valid only if you respect `id` values in previous currencies.yml):
1. Move existing config/currencies.yml to config/seed/currencies.yml.
2. Edit config/seed/currencies.yml to match new structure:
1. Rename `quick_withdraw_max` => `quick_withdraw_limit`.
2. Rename `blockchain` => `transaction_url_template`.
3. Rename `address_url` => `wallet_url_template`.
4. Replace `coin: true` with `type: coin`.
5. Replace `coin: false` with `type: fiat`.
6. Move variables `json_rpc_endpoint`, `api_client`, `bitgo_test_net`, `bitgo_wallet_id`, `bitgo_wallet_address`, `bitgo_wallet_passphrase`, `bitgo_rest_api_root`, `bitgo_rest_api_access_token`, `wallet_url_template`, `transaction_url_template` to variable `options` (Ruby Hash).
7. Add variable `precision: 8` (for coins) & `precision: 2` (for fiats) where it is missing.
8. Add variable `visible: true` where it is missing.
9. Add variable `base_factor: 1` for fiats where it is missing.
10. Remove variables: `assets`.
3. Execute `bundle exec rake db:migrate db:seed`.
### New features ###
* [#572](https://github.com/rubykube/peatio/pull/572): Add support for PostgreSQL.
It is now possible to run Peatio with PostgreSQL instead of MySQL. Check docs/databases/postgresql.md for the guide.
* [#602](https://github.com/rubykube/peatio/pull/602): Backport support for Rippled.
`CoinAPI::XRP` is back. We refactored it to match specs of new cryptocurrency client (`CoinAPI::BaseAPI`), removed all calls to deprecated v1 REST API, updated configuration files, added specs for integration with Ripple, and refactored the client to respect the latest JSON RPC API.
### Enhancements ###
* [#603](https://github.com/rubykube/peatio/pull/603): Add missing specs for auth via Barong OAuth server.
* [#607](https://github.com/rubykube/peatio/pull/607): Add missing specs for ability to disable cabinet or markets UI.
* [#605](https://github.com/rubykube/peatio/pull/605): Make UI handle long deposit addresses.
UI is now ready to handle long deposit addresses at «Funds» page. This is necessary for Ripple addresses with destination tag included.
* [#618](https://github.com/rubykube/peatio/pull/618): Add automatic validation for numeric and string database table fields.
We included Gem `validates_lengths_from_database` which is able to validate limits for various database field types.
* [#633](https://github.com/rubykube/peatio/pull/633): Add idempotency behavior for deposit address generation.
The patch allows multiple calls to PaymentAddress#enqueue_address_generation which helps to ensure address is always single, and enqueued for generation, if it is blank.
* [#635](https://github.com/rubykube/peatio/pull/635): Update MacOS setup instructions.
* [#641](https://github.com/rubykube/peatio/pull/641): Reload page after canceling withdraw.
The patch adds page reload after user cancels the withdraw.
* [#639](https://github.com/rubykube/peatio/pull/639): Automatically update lib/peatio/version.rb from TravisCI.
`Peatio::VERSION` will be now automatically updated by TravisCI builds (ci/bump.rb).
* [#636](https://github.com/rubykube/peatio/pull/636): Replace Gem eco with ejs.
We replaced eco with EJS since eco is much simpler and is maintained.
* [#637](https://github.com/rubykube/peatio/pull/637): Remove obsolete deployment & pipeline stuff (scripts and configs).
### Fixes ###
* [#611](https://github.com/rubykube/peatio/pull/611): Fix typo in app/models/member.rb related to update for OAuth token.
The key `level` was used by a typo to fetch refreshed OAuth2 token for keeping member profile updated in the future.
* [#617](https://github.com/rubykube/peatio/pull/617): Fix UI bug preventing from selecting timeranges at markets page.
* [#610](https://github.com/rubykube/peatio/pull/610): Fix admin controller inheritance issue preventing from viewing deposit & withdraw details.
The issue is related to invalid resolution of Ruby `BaseController` constant.
* [#627](https://github.com/rubykube/peatio/pull/627): Require latest stable Chrome via .travis.yml & update chromedriver-helper to 1.2.0.
Recent update of Chrome combined with missing requirement for latest stable Chrome in .travis.yml caused TravisCI build to fail.
* [#630](https://github.com/rubykube/peatio/pull/630): Fix failing specs randomized with seed 6911.
* [#631](https://github.com/rubykube/peatio/pull/631): Fix ReferenceError: log is not defined (JavaScript error at /documents/api_v2).

170
docs/releases/1.4.0.md Normal file
View File

@@ -0,0 +1,170 @@
## Peatio 1.4.0 (March 12, 2018) ##
### Overview ###
This release is focused on security upgrades which include:
1. Refactoring existing JWT implementation by adding validation for JWT fields.
2. Automatic member registration based on JWT payload.
3. Removal of keypair auth.
4. Removal requirement for private key to be stored at environment variable (now Peatio requires only public key for JWT to work).
The release also includes various fixes and improvements.
### Breaking changes ###
* [#629](https://github.com/rubykube/peatio/pull/629): Remove keypair authentication.
The patch removes all stuff related to APIv2 authentication using Hash-based Message Authentication Code (HMAC).
Some important components which are removed:
* `APIToken`
* `APIv2::Auth::KeypairAuthenticator`
* `Private::APITokensController`
* `APIv2::IncorrectSignatureError`
* `APIv2::TonceUsedError`
* `APIv2::InvalidTonceError`
* `APIv2::InvalidAccessKeyError`
* `APIv2::DisabledAccessKeyError`
* `APIv2::ExpiredAccessKeyError`
* `APIv2::OutOfScopeError`
All existing Peatio clients should think of upgrading to JWT, or wait until secure server-to-server API is released.
* [#620](https://github.com/rubykube/peatio/pull/620): Refactor withdraw destination: implement new fiat withdraw story, leverage existing withdraw API resources, and update UI.
The patch replaces `FundSource` in favor of `WithdrawDestination`.
Model `WithdrawDestination` works in STI mode providing `WithdrawDestination::Coin` and `WithdrawDestination::Fiat`.
Both `WithdrawDestination::Coin` and `WithdrawDestination::Fiat` are packed with common fields:
* `label`
`WithdrawDestination::Coin` is shipped with additional fields:
* `address`
`WithdrawDestination::Fiat` is shipped with typical bank withdraw fields:
* `bank_name`
* `bank_branch_name`
* `bank_branch_address`
* `bank_identifier_code`
* `bank_account_number`
* `bank_account_holder_name`
Instead of keeping common table structure we moved specific fields into JSON field called `details`.
API changes include:
* Withdraw entity: new field called `type`, available values are `fiat` and `coin`.
* Withdraw entity: field `address` (string) is replaced with `destination` object.
* Withdraw address entity replaced in favor of destination: includes `id`, `label`, `type`, `currency`, and all specific fields to withdraw destination type.
* `GET /withdraws/addresses` is now `GET /withdraws/destinations`.
* `POST /withdraws/addresses` is now `POST /withdraws/destinations`.
* `POST /withdraws/destinations`: mandatory params include `currency`, `label`, and specific fields to withdraw destination type.
* `DELETE /withdraws/addresses/:id` is now `DELETE /withdraws/destinations/:id`.
* `POST /withdraws`: parameter `address_id` renamed to `destination_id`.
`Member#withdraws` and `Member#withdraw_destinations` are now always ordered with `id DESC`.
`Private::FundSourcesController` is migrated to `Private::WithdrawDestinationsController`, `destroy` action is removed until we will denormalize withdraw fields, or find another solution for storing withdraw destination data.
* [#676](https://github.com/rubykube/peatio/pull/676): Stop keeping private key for JWT, use it only in specs.
The patch replaces `JWT_SHARED_SECRET_KEY` (private key) with `JWT_PUBLIC_KEY` (public key) for security reasons. So Peatio now will not store any private keys which is much better for security.
We removed all predefined values for `JWT_SHARED_SECRET_KEY` in all environments.
We included new guide for getting keypair to be used with JWT in config/application.yml (available after `bin/init_config`).
Migration steps:
1. Generate new keypair using guide from application.yml.
2. Update private key at your JWT provider.
3. Set public key value to `JWT_PUBLIC_KEY` at Peatio.
4. Ask JWT provider for new token.
5. Ensure API works by using cURL: `curl -H "Authorization: Bearer JWT" http://localhost:3000/api/v2/members/me`.
* [#661](https://github.com/rubykube/peatio/pull/661): Remove Member#jwt without replacements.
The patch removes dangerous method which was used only for testing purposes.
* [#662](https://github.com/rubykube/peatio/pull/662): Remove helper controller used for testing: Test::ModuleController & Test::MembersController.
The patch removed controllers & routes which was used for QA purposes. These resources could generate example members, and return them including JWT.
### New features ###
* [#657](https://github.com/rubykube/peatio/pull/657): Add on the fly member registration based on JWT payload (Barong only).
The patch implements automatic member registration based on JWT payload when using API (only for JWT provided by Barong).
How it works: When client makes request to API and passes header `Authorization: Bearer JWT` authenticator `APIv2::Auth::JWTAuthenticator` will decode, verify JWT, and, if JWT is issued by Barong, will register or update member.
JWT payload structure (see linked [commit at Barong](https://github.com/rubykube/barong/commit/3196b9ca0ff749be7158c6dbbf6b8c13a6ca9999)):
1. `email`: member email.
2. `uid`: used ID at barong (similar value to `sn` at Peatio).
3. `level`: member level represented as number (see available values at `Member::Levels`, app/enums/member/levels.rb).
4. `state`: member state (values are defined by Barong, some of them include `active`, `pending`), Peatio will set member to disabled unless `state` is `active`.
### Enhancements ###
* [#665](https://github.com/rubykube/peatio/pull/665): Update JWT specs by adding additional JWT fields.
The patch adds specs which cover most of common usage for the next fields:
1. iat
2. exp
3. jti
4. sub
5. iss
6. aud
* [#658](https://github.com/rubykube/peatio/pull/658): Update JWT gem to 2.1.x.
* [#669](https://github.com/rubykube/peatio/pull/669): Enable verification of special JWT payload fields.
The patch allows to customize which JWT fields should be validated by setting environment variables:
1. `JWT_ISSUER`
2. `JWT_AUDIENCE`
3. `JWT_DEFAULT_LEEWAY`
4. `JWT_ISSUED_AT_LEEWAY`
5. `JWT_EXPIRATION_LEEWAY`
6. `JWT_NOT_BEFORE_LEEWAY`
Get more info at config/application.yml (available after running `bin/init_config`).
Specs will now generate public and private keypair in runtime automatically.
* [#643](https://github.com/rubykube/peatio/pull/643): Update bin/init_config & bin/link_config according to new config templates structure and updated requirements for config/seed.
### Fixes ###
* [#616](https://github.com/rubykube/peatio/pull/616): Fix wrong blockchain explorer URL in deposit & withdrawal history.
The patch fixes interpolation issues with URL addresses displayed at user deposit/withdraw history, and in many places at admin panel. The wallet URL address template was interpolated using transaction ID, now it is interpolated with address.
* [#649](https://github.com/rubykube/peatio/pull/649): Fix broken market «Notify» On/Off buttons.
The feature was broken after migration currencies.yml to database. The patch restores previous behaviour.
* [#675](https://github.com/rubykube/peatio/pull/675): Fix order of commands in bin/setup to resolve issues with asset installation step.
The patch fixes related issues in workbench:
* [rubykube/workbench#25](https://github.com/rubykube/workbench/issues/25)
* [rubykube/workbench#27](https://github.com/rubykube/workbench/issues/27)
* [#674](https://github.com/rubykube/peatio/pull/674): Add missing DASH/USD market to markets.yml.
* [#677](https://github.com/rubykube/peatio/pull/677): Fix regression after [#372](https://github.com/rubykube/peatio/pull/372).
The patch resolved issues with broken websocket_api.rb daemon.

122
docs/releases/1.5.0.md Normal file
View File

@@ -0,0 +1,122 @@
## Peatio 1.5.0 (March 20, 2018) ##
### Overview ###
This release is focused on:
1. Extraction of trading UI to separate application.
2. Full dynamic support of currencies from database and full removal of any currency-specific code from Peatio.
3. Ability to develop & install Peatio plugins.
4. General fixes & improvements.
### Breaking changes ###
* [#449](https://github.com/rubykube/peatio/pull/449): Extract trading UI to separate component.
The patch moves trading UI assets and views to separate component called `peatio-trading-ui`. The extracted component lives at [GitHub repository](https://github.com/rubykube/peatio-trading-ui) and is based on Rails 5.1.
Migration steps include (we assume your Peatio is deployed at `peatio.tech`):
* You will need to add NGINX to your stack.
* Review NGINX configuration which can be found at `ci/nginx/server.conf`.
* The trick is that both Peatio and Trading UI are deployed on the same domain but are served conditionally by NGINX reverse proxy depending on the request path.
* Another trick is that both apps share the same cookies because they live on the same domain (however, trading UI doesn't do any decode/encode operations so there is not need for sharing `SECRET_KEY_BASE` between two apps).
* Trading UI app has separate asset prefix: `/trading-ui-assets`. So all requests which match `/\A\/trading-ui-assets\//` must be routed to trading UI app.
* The path to page with markets has also been changes from `/markets/:id` to `/trading/:market_id`. All requests which satisfy `/\A\/trading\//` must be routed to trading UI app.
* The trading UI app will first download variables for specified `market_id` (like `btcusd`) from Peatio by issuing `HTTP GET https://peatio.tech/markets/btcusd.json`, and then render Rails views according to received variables.
* The member is kept authenticated because trading UI app sends cookies via HTTP header to `https://peatio.tech/markets/btcusd.json`.
* The variable which controls Peatio root URL is called `PLATFORM_ROOT_URL`. Check more trading UI configuration variables at [`config/templates/application.yml.erb`](https://github.com/rubykube/peatio-trading-ui/blob/master/config/templates/application.yml.erb).
* We updated `.travis.yml` at Peatio so it automatically deploys trading UI locally with Docker and runs Selenium specs. Study `.travis.yml` for detailed examples on how to run & use trading UI.
* [#687](https://github.com/rubykube/peatio/pull/687): Refactor environment variables for Pusher.
The patch simplifies Pusher configuration and adds new variables for easy migration to Pusher Slanger.
The renamed variables:
* `PUSHER_KEY` => `PUSHER_CLIENT_KEY`.
* `PUSHER_WS_PORT` => `PUSHER_CLIENT_WS_PORT`.
* `PUSHER_WSS_PORT` => `PUSHER_CLIENT_WSS_PORT`.
* `PUSHER_ENCRYPTED` => `PUSHER_CLIENT_ENCRYPTED`.
The added variables:
* `PUSHER_SCHEME`: protocol used for publishing event from backend to Pusher.
* `PUSHER_CLIENT_WS_HOST`: to which WebSocket host should client connect.
* `PUSHER_CLIENT_HTTP_HOST`: alternative to WebSocket (polling).
The removed variables:
* `PUSHER_CLUSTER`: this variable doesn't fit well in context of Pusher Slanger. You should now use `PUSHER_HOST`, `PUSHER_CLIENT_WS_HOST`, and `PUSHER_CLIENT_HTTP_HOST` for configuration.
Check `config/application.yml` for more details and default values.
* [#694](https://github.com/rubykube/peatio/pull/694): Unify currency-specific models, controllers, routes, locales, stylesheets, and other components into type-specific.
The patch continues and fully finishes work from [#488 Move currencies.yml to database](https://github.com/rubykube/peatio/pull/488):
* All controllers (including user & admin) which stand for specific currency (like `BitcoinsController`, `DuffsController`) are now unified into `FiatsController` and `CoinsController` depending on currency type.
* The same store for models, views, locales, stylesheets and routes: `Deposits::Fiat`, `Deposits::Coin`, `Withdraws::Fiat`, `Withdraws::Coin`.
* The patch removes field `Currency#key` as it is not more needed. You must remove `key` from `config/seed/currencies.yml`.
* Peatio now adds much more attention to `Currency#type` and uses it smarter.
These changes are the first step to multifiat feature. Now Peatio is fully ready for adding any number of currencies by just issuing query to database.
Once we will add support for ERC20 tokens to Peatio it will be possible to add 500+ token-based currencies to Peatio by just populating database! Now you can do the same trick with any Bitcoin-compatiable currency. The one requirement for dynamically adding currencies to database is presence of currency API client (`CoinAPI`).
### New features ###
* [#698](https://github.com/rubykube/peatio/pull/698): Clear user session stored in Redis via API call `DELETE /api/v2/sessions`.
The patch adds ability for deleting all member sessions which are stored in Redis. This feature is useful for SPA which use JWT & OAuth server for solving identity question.
To use this feature issue `HTTP DELETE` request at `/api/v2/sessions` and provide valid JWT.
**IMPORTANT**: Your session is only and only deleted if server returns status 200, in other cases assume session is not fully deleted so you may be still signed in Peatio.
**IMPORTANT**: This is very important security feature so it was backported at older Peatio branches: `1.1`, `1.2`, and `1.3`.
* [#708](https://github.com/rubykube/peatio/pull/708): Add ability to install plugins.
The patch introduces very simple plugin for Peatio:
* Use `config/plugins.yml` to list wanted plugins. Each plugin is constructed from name, Git repository URL, commit hash, and path to file which should be required (optional, defaults to `index.rb`).
* Use `bin/install_plugins` to install listed plugins from `config/plugins.yml` to `vendor/plugins`.
* Use `bin/uninstall_plugins` to remove all installed plugins in `vendor/plugins`.
Get more information about plugin installation at `config/plugins.yml`.
Find example plugin at [peatio-plugin-example](https://github.com/rubykube/peatio-plugin-example).
### Enhancements ###
* [#689](https://github.com/rubykube/peatio/pull/689): Add development-related files to `.dockerignore`.
The patch adds several paths to `.dockerignore` which reduces time needed to build an image and it's size.
* [#696](https://github.com/rubykube/peatio/pull/696): Drop Account#in & Account#out fields.
The patch removes unused fields from table `accounts` (put in «Enhancements» since it doesn't break anything).
* [#702](https://github.com/rubykube/peatio/pull/702): Update the `nginx.conf` and `passenger.conf`.
The patch updates NGINX & Passenger configuration files to support type of installation without Docker. Please, keep in mind: we don't support this type of Peatio installation. We support Docker-only setups. So we may remove all non-Docker docs soon.
Thanks to [@shiftctrl-io](https://github.com/shiftctrl-io).
* [#688](https://github.com/rubykube/peatio/pull/688): Set collation on database.yml.
The patch sets `collation: utf8_general_ci` directly in `config/database.yml`.
### Fixes ###
* [#700](https://github.com/rubykube/peatio/pull/700): Fix broken authentication in WS.
The patch fixes retrieving of authentication token in `APIv2::WebSocketProtocol`.
This was a regression after [#629](https://github.com/rubykube/peatio/pull/629).
Now access key is fetched from payload (parameter is called `jwt`) instead of headers.

132
docs/releases/1.6.0.md Normal file
View File

@@ -0,0 +1,132 @@
## Peatio 1.6.0 (April 3, 2018) ##
### Overview ###
This release is focused on:
1. Migrating market pairs to database layer.
2. Implementation of `Management API v1`: server-to-server API with high privileges.
The release also includes various fixes and improvements.
### Breaking changes ###
* [#412](https://github.com/rubykube/peatio/pull/412): Migrate markets.yaml to database.
The patch moves `ActiveYaml::Base` model `Market` to database layer. All market pairs are now fully stored in database instead of YAML file.
**Migration steps**:
1. Copy `config/markets.yml` to `config/markets.old.yml` and to `config/seed/markets.yml`.
2. Make the next edits in `config/seed/markets.yml`:
2.1 Remove field `code` from all records.
2.2 Rename `sort_order` to `position`.
2.3 Rename `base_unit` to `ask_unit`.
2.4 Rename `quote_unit` to `bid_unit`.
2.5 Move `ask.fee` to `ask_fee`.
2.6 Move `bid.fee` to `bid_fee`.
2.7 Remove `ask.currency`.
2.8 Remove `bid.currency`.
2.9 Move `ask.fixed` to `ask_precision`.
2.10 Move `bid.fixed` to `bid_precision`.
3. Execute `bundle exec rake db:seed`.
### New features ###
* [#740](https://github.com/rubykube/peatio/pull/740): Implement API for server-to-server communication called `Management API`.
The API is designed for server-to-server communication. You can use this API for extending Peatio functionality or integrating, for example, custom payment processing service. The API is quite easy to use and is friendly with enterprise standards like accounting and analytics.
The authentication is based on JWT token in complete format allowing to have multiple signatures.
We developed and published new Ruby Gem for working with nested signatures in JWT. The Gem [jwt-multisig](https://rubygems.org/gems/jwt-multisig) lives at [GitHub repository](https://github.com/rubykube/jwt-multisig). You should use it for signing requests for Peatio from your service.
You can use `config/management_api_v1.yml` (available only after `bin/init_config`) for customization of security rules for the API. You are free to choose what signatures any API action requires, configure JWT verification options and, of course, set public keys used for verification of signatures. The security documentation for API is embedded in the `management_api_v1.yml` file.
The patch includes the next API actions:
* Ability to list deposits (including filters).
* Ability to list withdraws (including filters).
* Ability to get single deposit.
* Ability to get single withdraw.
* Ability to create deposit.
* Ability to create withdraw.
* Ability to accept deposit on Peatio and load money.
* Ability to submit withdraw for processing by Peatio.
* Ability to get server time.
The Swagger documentation for this API is available locally by visiting `http://localhost:3000/swagger?url=/management_api/v1/swagger` or by checking out `docs/api/management_api_v1.md`.
The deposit states were refactored:
* State `submitting` was renamed to `submitted`.
* State `cancelled` was renamed to `canceled`.
* State `checked` was removed.
* State `warning` was removed.
The withdraw states were refactored:
* State `submitting` was renamed to `prepared`.
* State `cancelled` was renamed to `canceled`.
* State `suspect` was renamed to `suspected`.
* State `done` was renamed to `succeed`.
The changes to `Member API v2` include:
* The changes to field `state` affect the next API endpoints: `GET /api/v2/deposits`, `GET /api/v2/deposit`, `GET /api/v2/withdraws`, `POST /api/v2/withdraws`.
* `POST /api/v2/withdraws` is now deprecated and will be removed in further releases.
* [#701](https://github.com/rubykube/peatio/pull/701): Ability to retrieve solvency information through API.
The patch adds several endpoints designed to work with solvency information:
* `/api/v2/solvency/liability_proofs/latest`
* `/api/v2/solvency/liability_proofs/partial_tree/mine`
You can open Swagger documentation locally by visiting `http://localhost:3000/swagger?url=/api/v2/swagger` or by checking out `docs/api/member_api_v2.md`.
### Enhancements ###
* [#727](https://github.com/rubykube/peatio/pull/727): Update loofah to 2.2.
The patch fixes reported security issues.
* [#648](https://github.com/rubykube/peatio/pull/648): Speed up Docker image build.
The patch is an experimental attempt to speed up Docker images build on TravisCI.
* [#721](https://github.com/rubykube/peatio/pull/721): Remove `Currency#quick_withdraw_limit`.
The patch removes unnecessary convertation of `quick_withdraw_limit` to `BigDecimal`.
* [#726](https://github.com/rubykube/peatio/pull/726): Remove translations not used by Peatio.
The patch removes leftovers from translation data after extraction of trading UI to separate application.
### Fixes ###
* [#741](https://github.com/rubykube/peatio/pull/741): Stop «Exchange assets» tab from breaking without liability proof generated && remove redundant `AssetsController#partial_tree`.
The patch applies changes so page «Exchange assets» will now handle situation when solvency information is not available.
* [#737](https://github.com/rubykube/peatio/pull/737): Display `Currency#code` instead of `Currency#to_s` at `/admin/proofs`.
* [#776](https://github.com/rubykube/peatio/pull/776): Handle specific response for ETH wallet from BitGo when generating new address.
The BitGo API reference [method for creation of new address](https://bitgo.github.io/bitgo-docs/?shell#create-address) for some reasons returns different response when used with ETH wallets. This doesn't work with Peatio will. We don't know why this happens so we pushed patch which can handle such response. We believe BitGo may have another undocumented incompatibilities.
The patch was also pusher to branch `1-5-stable`.

241
docs/releases/1.7.0.md Normal file
View File

@@ -0,0 +1,241 @@
## Peatio 1.7.0 (April 19, 2018) ##
### Overview ###
This release is focused on:
1. Ability to manage currencies in admin panel.
2. Ability to manage market pairs in admin panel.
3. Support for multiple fiat currencies.
4. Migration to Bootstrap 4 from Bootstrap 3.
5. Brand-new Events API on top of AMQ protocol used for extending Peatio (experiment).
6. Lot of refactoring and improvements after major changes in 1.6.
The release also includes various fixes and improvements.
### Breaking changes ###
* [#800](https://github.com/rubykube/peatio/pull/800): Remove «WithdrawDestination» model in favor of RID (recipient ID).
The patch makes Peatio free out of all bank credentials, bank accounts and other stuff. People should think about Peatio like microservice for wallet management and trading. Applications which use Peatio for these kind of tasks are now able to link withdraw on Peatio to their's own using field called `rid` (recipient ID). This field is required and must uniquely identify bank account (for cryptocurrency withdraws it must identity wallet address in blockchain).
The changes to API:
* `GET /api/v2/withdraws/destinations`, `POST /api/v2/withdraws/destinations`: API calls removed.
* Request formats of `GET /api/v2/withdraws`, `POST /api/v2/withdraws`: parameter `destination_id` replaced with `rid`.
* Response formats of `GET /api/v2/withdraws`, `POST /api/v2/withdraws`: `txid` is not exposed as `blockhain_txid`, `destination` replaced with `rid`.
* Request formats of `POST /management_api/v1/withdraws/new`: parameter `destination_id` was removed.
IMPORTANT: The patch drops table `withdraw_destinations`. Be sure to backup the data before running migrations. The migration will automatically calculate field `rid` from `Withdraw#bank_account_number` (for fiat withdraws) and `Withdraw#address` (for crypto).
Also fixes: #799, #772.
The patch merged to 1.6 and up.
* [#820](https://github.com/rubykube/peatio/pull/820): Remove `Deposit#fund_extra`, `Deposit#fund_uid` and usages.
The patch removes useless fields from deposit: `fund_extra`, `fund_uid`. Be sure to backup your data in case you need these fields.
* [#816](https://github.com/rubykube/peatio/pull/816): Remove `Withdraw#sn` and all usages.
The patch removed useless withdraw model fields: `sn`. Be sure to backup this field in case you need the values.
* [#829](https://github.com/rubykube/peatio/pull/829): Replace `PaymentTransaction` in favor of `Deposit`.
The patch drops `PaymentTransaction` model in favor of `Deposit` which simplifies the code a lot.
We also improved database indices for deposits.
The breaking changes include:
* Response format of `GET /api/v2/deposits`, `GET /api/v2/deposit`: `done_at` is now exposed as `completed_at`.
* Response format of `POST /management_api/v1/deposits`, `POST /management_api/v1/deposits/get`, `POST /management_api/v1/deposits/new`, `PUT /management_api/v1/deposits/state`: added `blockchain_confirmations` to response.
* [#850](https://github.com/rubykube/peatio/pull/850): Remove mailing stuff from Peatio.
The patch removes mailers, views, gems, variables and documentation related to mailing. Now Peatio will not send any emails. It means you will need to implement your own mailing system using upcoming Peatio Events API. For example, you can send mail «Your deposit successfully accepted» when your application received event from Peatio (via AMQP) and deposit payload has status «accepted». This is very flexible way of extending Peatio with any amount of functionality. If you really need mails stay on 1.6.
* [#881](https://github.com/rubykube/peatio/pull/881): Embed «DepositChannel» in «Currency».
The patch migrates `config/deposit_channels.yml` to database layer.
The migration steps include:
1. Rename `config/deposit_channels.yml` to `config/deposit_channels.old.yml`.
2. Execute `bundle exec rake db:migrate`.
The patch adds `Currency#deposit_confirmations` which defines how many confirmations in blockchain transaction must receive to be accepted on Peatio.
* [#884](https://github.com/rubykube/peatio/pull/884): Embed «WithdrawChannel» in «Currency».
The patch migrates `config/withdraw_channels.yml` to database layer.
1. Rename `config/withdraw_channels.yml` to `config/withdraw_channels.old.yml`.
2. Execute `bundle exec rake db:migrate`.
The patch adds `Currency#withdraw_fee` which defined fixed fee for withdraw.
### New features ###
* [#781](https://github.com/rubykube/peatio/pull/781): Ability to manage market pairs using admin panel.
The patch adds ability to manage market pairs using admin panel (`/admin/markets`). You can create new markets, edit trading fees, change the order of markets, etc.
* [#828](https://github.com/rubykube/peatio/pull/828): Migration to Bootstrap 4.
The patch migrates from Bootstrap 3 to Bootstrap 4 improving user experience in both cabinet and admin panel.
* [#825](https://github.com/rubykube/peatio/pull/825): Ability to manage currencies using admin panel.
The patch adds ability to manage currencies using admin panel (`/admin/currencies`). You can create new currencies, edit API settings, change symbols, etc.
* [#826](https://github.com/rubykube/peatio/pull/826): Add support for multiple fiat currencies.
The patch finally adds support for multiple fiat currencies. You can add currency in admin panel, create market pair for it, deposit some money and start trading.
New variable has been added: `DISPLAY_CURRENCY`. This variable defines currency which is used to display amount of other currencies. Check more about it in `config/application.yml`.
* [#914](https://github.com/rubykube/peatio/pull/914): Event API based on AMQP used for extending Peatio (experiment).
This feature allows other applications to extend Peatio functionality (like business logic) by relying on AMQP (RabbitMQ) standard.
Checkout the specification `docs/specs/event_api.md` for complete details.
### Enhancements ###
* [#782](https://github.com/rubykube/peatio/pull/782): Improved English phrasing in README.
The patch updated README with fixes and improvements.
* [#783](https://github.com/rubykube/peatio/pull/783): Fix typos and update details for Ubuntu installation instruction.
The patch updates docs for Ubuntu installation. IMPORTANT: We don't support this type of installation, we support Docker type of installation only.
* [#762](https://github.com/rubykube/peatio/pull/762): Add gem «bullet».
The patch adds gem bullet to development dependencies which helps to resolve N+1 problems and optimize SQL.
* [#808](https://github.com/rubykube/peatio/pull/808): Suppress warnings from figaro.
The patch tweaks `config/application.yml` so figaro doesn't output warnings anymore.
* [#815](https://github.com/rubykube/peatio/pull/815): Set member API version to match Peatio version.
The patch sets version in API docs the same as version of Peatio.
* [#751](https://github.com/rubykube/peatio/pull/751): Hide «unsecure protocol» warning from Bundler.
* [#832](https://github.com/rubykube/peatio/pull/832): Ignore .yarnrc and .cache in Git.
* [#833](https://github.com/rubykube/peatio/pull/833): Add ability to set UID and GID as Docker build args.
Merged to 1.6 and up.
* [#794](https://github.com/rubykube/peatio/pull/794): Remove trading UI leftovers in Peatio.
The patch removes lot of translations, assets & views which was still in Peatio ever after extraction of trading UI.
* [#844](https://github.com/rubykube/peatio/pull/844): Remove Swagger UI leftovers.
The patch removes all custom Swagger UI dependencies.
* [#836](https://github.com/rubykube/peatio/pull/836): Remove gem Slim.
* [#860](https://github.com/rubykube/peatio/pull/860): Finish Capybara tests in `features/admin/withdraw_spec.rb`.
The patch completes pending acceptance tests for admin withdraw page.
* [#885](https://github.com/rubykube/peatio/pull/885): Gemfile optimization: `eventmachine` & `em-websocket`.
The patch changes Gemfile to require the gems listed above only when they are needed (in `lib/daemons/websocket_api.rb`).
* [#906](https://github.com/rubykube/peatio/pull/906): Extend type of fee columns to match type of amount columns in database (`DECIMAL(32, 16)`).
The patch ensures database can store fee equal to 100% of amount.
* [#896](https://github.com/rubykube/peatio/pull/896): Update omniauth-barong version (compatibility with Barong 1.7).
### Fixes ###
* [#791](https://github.com/rubykube/peatio/pull/791): Fix «NoMethodError: undefined method 'fetch' for #<OpenSSL::PKey::RSA>».
The patch fixes error related to parsing of `config/management_api_v1.yml` at `config/initializers/jwt.rb`. Merged to 1.6 and up.
* [#709](https://github.com/rubykube/peatio/pull/709): Add missing translation for «ORDER FULFILLED» (account version reason) and fix spelling.
The patch adds missing locale entries.
* [#769](https://github.com/rubykube/peatio/pull/769): Add missing step for installation with PostgreSQL.
The patch updated docs for installation with PostgreSQL.
* [#811](https://github.com/rubykube/peatio/pull/811): `PUSHER_CLIENT_ENCRYPTED` is ignored when value is «false».
The value of variable `PUSHER_CLIENT_ENCRYPTED` was ignored if set to `false`. Merged to 1.5 and up.
* [#807](https://github.com/rubykube/peatio/pull/807): Page should not be reloaded after creation of withdraw.
The patch prevents page from being reloaded after withdraw cancelation. Peatio must be correctly configured with Slanger (or Pusher) so the changes will be reflected without reload of page.
* [#806](https://github.com/rubykube/peatio/pull/806): Get rid of errors «Undefined method may_*?» for deposits and withdraws.
The patch fixes bugs which popped out after refactoring of deposit & withdraw states.
Merged to 1.6 and up.
* [#796](https://github.com/rubykube/peatio/pull/796): Fix failing specs with seed 59081 & 39808 (Capybara + DatabaseCleaner issue).
The patch updates spec configuration for better compatibility between DatabaseCleaner & Capybara.
* [#797](https://github.com/rubykube/peatio/pull/797): Fixes & specs for updated BitGo API (address creation issue).
The patch updates existing `CoinAPI::BitGo#create_address!` to be compatible with unexpectedly updated BitGo API and adds support for async address generation.
* [#839](https://github.com/rubykube/peatio/pull/839): Add missing `Private::DepositsController#destroy` action (couldn't cancel deposit).
Merged to 1.5 and up.
* [#856](https://github.com/rubykube/peatio/pull/856): Enqueue new matching engine after market create.
The patch fixes issues:
* List of orders is not displayed in trading UI for new markets.
* Cancellation of orders doesn't work on markets added from admin panel.
Merged to 1.6 and up.
* [#870](https://github.com/rubykube/peatio/pull/870): Fix typos in README.
* [#874](https://github.com/rubykube/peatio/pull/874): Don't create payment addresses for fiat accounts. Additional checks for address generation.
The patch adds additional checks which ensure payment address will not be generated for fiat accounts.
Previously there was a way to enqueue generation of payment address for fiat currency. This resulted in infinite error at deposit address generation worker. Now this is finally fixes and patched.
Merged to 1.5 and up.
* [#880](https://github.com/rubykube/peatio/pull/880): Various fixes after migration to BS4.
* [#892](https://github.com/rubykube/peatio/pull/892): Fix error in OrderBook entity caused by class loading order bug in Grape.
The patch fixes overlapping between constants `Order` and `APIv2::Entities::Order`.
Merged to 1.5 and up.
* [#879](https://github.com/rubykube/peatio/pull/879): Store fee in `Order#fee`.
The patch embeds field `fee` in table `orders`. Previously the value was stored only in market and retrieved from it every time. This was a critical bug which prevented orders from showing real fee value at the moment when order was executed (it displayed only the latest value retrieved from market).
Merged to 1.6 and up.

163
docs/releases/1.8.0.md Normal file
View File

@@ -0,0 +1,163 @@
## Peatio 1.8.0 (May 3, 2018) ##
### Overview ###
This release is focused on:
1. Support for ERC20 tokens.
2. Fixing issues at all available APIs: Events API, Management API v2 & Member API v2.
3. Improvements for transaction processing mechanisms.
4. Fixing UI issues.
The release doesn't provide lot of new feature, instead it is focused on stabilization of current codebase.
### Breaking changes ###
* [#913](https://github.com/rubykube/peatio/pull/913): All wallet addresses, transaction IDs, TIDs, RIDs are now case sensitive.
The next migration files are must-learn before doing any upgrades:
* https://github.com/rubykube/peatio/pull/913/files#diff-685a1e4a0464f3358e0aaba59188992c
* https://github.com/rubykube/peatio/pull/913/files#diff-4d9437ddbba478de18ee9a1d044f3be0
Please, also be sure to checkout the new variable for currencies: `case_sensitive`. This variable determines if wallet addresses and transaction IDs are case sensitive or insensitive. Be sure to set the correct value for your currencies.
* [#1037](https://github.com/rubykube/peatio/pull/1037): Replace state to action in withdraws and change behaviour of initial withdraw state (Management API v1).
Changes to **`POST /management_api/v1/withdraws/new`**
Now the behaviours for fiat and crypto withdraws are different.
*Fiat*: money are immediately locked, withdraw state is set to «submitted», system workers will validate withdraw later against suspected activity, and assign state to «rejected» or «accepted». The processing will not begin automatically. The processing may be initiated manually from admin panel or by PUT /management_api/v1/withdraws/action.
*Coin*: money are immediately locked, withdraw state is set to «submitted», system workers will validate withdraw later against suspected activity, validate withdraw address and set state to «rejected» or «accepted». Then in case state is «accepted» withdraw workers will perform interactions with blockchain. The withdraw receives new state «processing». Then withdraw receives state either «succeed» or «failed».
The parameter `state` replaced with `action`. The available values include:
* `process`: system will lock the money, check for suspected activity, validate recipient address, and initiate the processing of the withdraw. The fiat withdraws will be completed immediately while crypto withdraws will be processed by workers since they require interaction with blockchain.
Migration steps:
* If you depend on `state: :prepared` you will need to review the logic of your app because it is now not possible to create withdraw with no money locked.
* If you depend on `state: :submitted` you can safely remove this parameter from payload.
Changes to **`PUT /management_api/v1/withdraws/state`**
This route changed to `PUT /management_api/v1/withdraws/action`.
The parameter `state` replaced with `action`. The available values include:
* `process`: system will lock the money, check for suspected activity, validate recipient address, and initiate the processing of the withdraw. The fiat withdraws will be completed immediately while crypto withdraws will be processed by workers since they require interaction with blockchain.
* `cancel`: system will mark withdraw as «canceled», and unlock the money (if they were locked).
Migration steps:
* `state: :submitted` is no longer supported in this call. If you want to initiate the processing of withdraw pass `action: :process`.
* If you depend on `state: :canceled` replace it with `action: :cancel`.
### New features ###
* [#913](https://github.com/rubykube/peatio/pull/913): Add support for ERC20 tokens.
The patch adds support for ERC20 tokens.
Read more about how to use this feature at:
* config/seed/currencies.yml.erb (find currency `TRST`).
* docs/peatio/erc20.md
* docs/peatio/testnet/erc20.md
* [#980](https://github.com/rubykube/peatio/pull/980): Ability to establish cookie-based session using API.
The patch adds new Member API v2 call `POST /api/v2/sessions` which allows to establish classical cookie-based session which expires along with JWT expiration time. It may be useful when Peatio is used as backend for SPA frontend along with existing Trading UI (which is cookie-based).
* [#915](https://github.com/rubykube/peatio/pull/915): Add ability to enable fiat deposit fee.
It is now possible to set fiat deposit fee (fixed size only).
* [#935](https://github.com/rubykube/peatio/pull/935): Ability to get deposit, withdraw and trading fees using Member API v2.
The patch adds public calls: `GET /api/v2/fees/deposit`, `GET /api/v2/fees/withdraw`, `GET /api/v2/fees/trading`.
* [#1033](https://github.com/rubykube/peatio/pull/1033): Expose account balance via Management API v1.
The patch adds new Management API v1 calls: `POST /management_api/v1/accounts/balance`.
Check more info at docs/api/management_api_v1.md.
### Enhancements ###
* [#931](https://github.com/rubykube/peatio/pull/931): Update omniauth-barong to 0.1.4.
The patch updates gem version and enabled Peatio to support newer Barong versions.
* [#922](https://github.com/rubykube/peatio/pull/922): Remove «Pusher not available» panel from Peatio UI.
* [#946](https://github.com/rubykube/peatio/pull/946): Treat Barong levels higher then or equal to three as «identity verified».
* [#961](https://github.com/rubykube/peatio/pull/961): Retry on all Capybara errors in tests (helps to run test on slow hardware).
* [#988](https://github.com/rubykube/peatio/pull/988): Remove legacy ActiveYAML stuff.
* [#992](https://github.com/rubykube/peatio/pull/992): Remove ability to select currency for fiat deposit, use currency code in URL instead.
* [#1012](https://github.com/rubykube/peatio/pull/1012): Permit cryptocurrency transactions between internal recipients.
* [#1027](https://github.com/rubykube/peatio/pull/1027): Add logging to Grape APIs.
### Fixes ###
* [#924](https://github.com/rubykube/peatio/pull/924): Various user interface fixes and improvements after migrating to Bootstrap 4 (for both user cabinet and admin).
* [#937](https://github.com/rubykube/peatio/pull/937): Various admin interface style fixes.
* [#994](https://github.com/rubykube/peatio/pull/994): Various UI fixes.
* [#918](https://github.com/rubykube/peatio/pull/918): Update documentation for Bitcoin walletnotify.
* [#949](https://github.com/rubykube/peatio/pull/949): Disable automatic processing for fiat withdraws and bring back ability to cancel withdraw in admin panel.
* [#942](https://github.com/rubykube/peatio/pull/942): Update conditions for fiat withdraw button (force manual processing, fixes sticky withdraws).
* [#956](https://github.com/rubykube/peatio/pull/956): Limit trading fee to 50%.
The patch adds validations & migrations which prevents user from settings trading fees over 50%.
* [#965](https://github.com/rubykube/peatio/pull/965): Add missing translations for withdraw states.
* [#958](https://github.com/rubykube/peatio/pull/958): Submit amounts as strings, update String#to_d to match Rails behaviour, add specs for extremely precise amounts.
* [#969](https://github.com/rubykube/peatio/pull/969): Always use legacy Bitcoin Cash addresses.
The patch converts BCH addresses from «Cash Address» format to legacy so it is compatible with most wallets & exchanges.
* [#976](https://github.com/rubykube/peatio/pull/976): Remove «--depth=1» from git clone in bin/install_plugins.
The patch fixes error which prevented from installing specific version of plugin (it was always master).
* [#989](https://github.com/rubykube/peatio/pull/989): Fix typos in docs/specs/event_api.
* [#984](https://github.com/rubykube/peatio/pull/984): Fix for BitGo ETH address generation.
* [#998](https://github.com/rubykube/peatio/pull/998): Submit withdraw after creation via API.
The patch fixes sticky withdraws created via Member API v2.
* [#1008](https://github.com/rubykube/peatio/pull/1008): Add «deposit_confirmations» to config/seed/currencies.yml.erb.
* [#1014](https://github.com/rubykube/peatio/pull/1014): Fix disappearing security_configuration when module reloads.
* [#1022](https://github.com/rubykube/peatio/pull/1022): Fix «[object Object]» problem in API docs, add bin/bump for updating versions & tweak ci/bump.rb.
* [#1028](https://github.com/rubykube/peatio/pull/1028): Tweak lib/daemons/coins.rb for stability.
The patch improves speed and stability of processing incoming transactions and fixes bug related to sticky daemon on processing ERC20 transactions.

172
docs/releases/1.9.0.md Normal file
View File

@@ -0,0 +1,172 @@
## Peatio 1.9.0 (August 9, 2018) ##
### Overview ###
We are pleased to present Peatio Open Source 1.9.0.
This release includes significant new features, numerous functional fixes and enhancements. Peatio 1.9.0 came out with a rewrite of Blockchain synchronisation daemon solving major design flaw of old original Peatio. Multi-tier wallet system is another great implemented feature helping achieve digital funds protection by using wallets segregation with specific access policies and flexible multi-signature settings. Among the other nice features such as Admin Interface for advanced Blockchain/Wallet management, this release is also focused on:
1. Multi Wallet support.
2. New Blockchain synchronization mechanism.
3. Full ERC20 tokens support.
4. Splitting of Blockchain read and write Services and Clients.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- [#1404](https://github.com/rubykube/peatio/pull/1404): Adding blockchain model, database seeds, service and client.
The next seed and migration files are must-learn before doing any upgrades:
- https://github.com/rubykube/peatio/pull/1404/files#diff-6be627e8bb77b25dcdf2c972d3c873ec
- https://github.com/rubykube/peatio/pull/1404/files#diff-91027e648f4292cd6ec8f7e11a43a669
Some of Blockchain configuration were extracted from Currencies. Blockchain model, service and client performs read operation and process blockchain blocks one by one. It responsible for coin deposit or withdraw state updates and deposit detection.
- [#1404](https://github.com/rubykube/peatio/pull/1404): Adding wallet model, database seeds, service and client.
The next seed and migration files are must-learn before doing any upgrades:
- https://github.com/rubykube/peatio/pull/1404/files#diff-3ac13d4e0c5c496b426d40b62db793b5
- https://github.com/rubykube/peatio/pull/1404/files#diff-1fc2b7b6df8dbd6da6bce9966b74a3e8
Wallet configurations were extracted from Currencies API client configuration. Wallet model, service and client performs write operation and responsible for deposit address creation, deposit collection, deposit collection fees transfering, and withdraw creation..
- [#1518](https://github.com/rubykube/peatio/pull/1518): Currencies dead code clean up.
The next seed and migration files are must-learn before doing any upgrades:
- https://github.com/rubykube/peatio/pull/1518/files#diff-eb833ff83c1af2e978d647f035f7d1ac
- https://github.com/rubykube/peatio/pull/1404/files#diff-91027e648f4292cd6ec8f7e11a43a669R17
Currencies model simplify. Now currency model doesn't store any API specific configuration and wallet secrets all this configuration where extracted to Blockchain and Wallet models.
- [#1458](https://github.com/rubykube/peatio/pull/1458): Include PublishToRabbitMQ GenerateJWT Event API middlewares by default.
The next configuration file is must-learn before upgrading:
- https://github.com/rubykube/peatio/commit/fa041a6ba8ba586ffc9f4095b1f4f46e2df6b017#diff-81b753b02c902d26e3b837d7814c5244R172
Now all events are pulished to RabbitMQ as in form of JWT messages by default instead of abstract RabbitMQ message.
### New features ###
* [#1404](https://github.com/rubykube/peatio/pull/1404): This pull request provides bunch of functional features and fixes:
* Blockchain model and Database seeding
* Adding wallet seeding
* Adding wallet model
* Fix STI problem
* Add missing associations
* Fix indexes order
* Adding factories and a test stub
* BlockchainService #process_blockchain deposits with proof of work [#1417](https://github.com/rubykube/peatio/pull/1417)
* Ability to register a blockchain/wallet from Admin Panel [#1422](https://github.com/rubykube/peatio/pull/1422)
* Revert some changes (related to #1422)
* Single BlockchainService per Blockchain [#1424](https://github.com/rubykube/peatio/pull/1424)
* Added Wallet/Blockchain validations [#1429](https://github.com/rubykube/peatio/pull/1429)
* Confirm withdrawals in BlockchainService #process_blockchain [#1427](https://github.com/rubykube/peatio/pull/1427)
* Rebase on master
* Bitcoin Blockchain Service [#1444](https://github.com/rubykube/peatio/pull/1444)
* Improve BlockchainService logger. Wallet & Blockchain bugfixes [#1474](https://github.com/rubykube/peatio/pull/1474)
* Add Blockchain Key In Currency [#1473](https://github.com/rubykube/peatio/pull/1473)
* Remove CoinAPI & daemons. Rename Client to BlockchainClient [#1476](https://github.com/rubykube/peatio/pull/1476)
* BlockchainService improve performance
* Fix specs
* Replace Confirmation With Block Number [#1463](https://github.com/rubykube/peatio/pull/1463)
* Add gateway & max_balance to wallets [#1478](https://github.com/rubykube/peatio/pull/1478)
* Wallet per currency
* WalletService module and WalletService::Base class [#1479](https://github.com/rubykube/peatio/pull/1479)
* DepositCollectionFees worker for ERC20 [#1489](https://github.com/rubykube/peatio/pull/1489)
* Litecoin/Dash/BitcoinCash Blockchain Services [#1475](https://github.com/rubykube/peatio/pull/1475)
* Updates for admin panel [#1501](https://github.com/rubykube/peatio/pull/1501)
* Fix erc20 deposit for tx with empty receipt [#1502](https://github.com/rubykube/peatio/pull/1502)
* Fix wrong client for existing blockchain on admin panel [#1504](https://github.com/rubykube/peatio/pull/1504)
* Bitgo wallet Client/Service [#1491](https://github.com/rubykube/peatio/pull/1491)
* Fixed withdraw stuck in confirming [#1507](https://github.com/rubykube/peatio/pull/1507)
* Improved dynamic txn fees for bitcoind/bitgo [#1509](https://github.com/rubykube/peatio/pull/1509)
* Feature/blockchains wallets [#1510](https://github.com/rubykube/peatio/pull/1510)
* [#1368](https://github.com/rubykube/peatio/pull/1368): Add 24 hours currency trades API endpoint.
This patch adds public call for getting currency trades performed within the last 24h: GET /v2/currency/trades.
Check more info at docs/api/member_api_v2.md.
* [#1433](https://github.com/rubykube/peatio/pull/1433): Add API endpoint for currencies.
This patch adds public call for getting the list of currencies: GET /v2/currencies.
Check more info at docs/api/member_api_v2.md
* [#1501](https://github.com/rubykube/peatio/pull/1501): Updates for admin panel.
This patch gives the ability to to register a blockchain/wallet from Admin Panel.
* [#1463](https://github.com/rubykube/peatio/pull/1463): Replace Confirmation With Block Number.
This patch replaces confirmations field in withdraw and currency model with block_number. So confirmations amount is updated dynamically.
* [#1460](https://github.com/rubykube/peatio/pull/1460): Support minimum price for Order.
* [#1318](https://github.com/rubykube/peatio/pull/1318): Send label when generating BitGo address.
### Enhancements ###
* [#1377](https://github.com/rubykube/peatio/pull/1377): Document every daemon.
The list and purpose of each Peatio daemon is described in [docs/daemons.md](docs/daemons.md).
* [#1342](https://github.com/rubykube/peatio/pull/1342): Ability to get data between some time interval (time_from, time_to) in GET /api/v2/k.
* [#1493](https://github.com/rubykube/peatio/pull/1493): Add more details for the API docs.
* [#1517](https://github.com/rubykube/peatio/pull/1517): Improved updation of blockchain height.
### Fixes ###
* [#1450](https://github.com/rubykube/peatio/pull/1450): Change Default Domain To peatio.tech.
* [#1526](https://github.com/rubykube/peatio/pull/1526): Change Currency Id And Market Id Limit.
* [#1402](https://github.com/rubykube/peatio/pull/1402): Fix migration multiple_deposit_addresses.
* [#1492](https://github.com/rubykube/peatio/pull/1492): Fix typo in setup-osx.md documentation.
* [#1529](https://github.com/rubykube/peatio/pull/1529): Code polish and minor bugfix.
* [#1518](https://github.com/rubykube/peatio/pull/1518): Currencies dead code clean up.
* [#1533](https://github.com/rubykube/peatio/pull/1533): Edit comments in templates for wallets.yml.

16
docs/releases/2.0.0.md Normal file
View File

@@ -0,0 +1,16 @@
## Peatio 2.0.0 (February 22, 2019) ##
### Overview ###
We are pleased to present Peatio Open Source 2.0.0.
This release concentrated on fundamental architecture changes and mostly focused on:
1. Double Entry Accouting system integration.
2. Basic Asset Liability Revenue and Expense operations management.
3. API Gateway integration.
4. Major API reorganization & improvements.
This release notes describes changes but doesn't provide migrations steps
since such a major updates requires deep source code knowledge.
We advice to install 2.0.0 from scratch

66
docs/releases/2.1.0.md Normal file
View File

@@ -0,0 +1,66 @@
## Peatio 2.1.0 (April 22, 2019) ##
### Overview ###
We are pleased to present Peatio Open Source 2.1.0.
This release concentrated on new v2 architecture related improvements and dependency updates:
1. Remove legacy Member UI.
2. Upgrade Ruby on Rails to 5.2.
3. Upgrade ruby to 2.6.2.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- [#2051](https://github.com/rubykube/peatio/pull/2051): Remove legacy member UI
Peatio legacy Member UI was not supported for a long time and deprecated in 2.0.0.
We have totally deleted Member UI from so now there is only Admin panel UI left in Peatio.
- [#2091](https://github.com/rubykube/peatio/pull/2091): Remove deprecated fees API
*public/fees/withdraw*, *public/fees/deposit*, *public/fees/trading*
API endpoints were removed in favour of
*public/markets*, *public/currencies*
- [#2090](https://github.com/rubykube/peatio/pull/2090): Remove plugin API v1
We advice to use Plugin API v2 instead. See more in [plugins](../plugins.md)
- [#2121](https://github.com/rubykube/peatio/pull/2121): Unify trade taker_type with Ranger and api
### New Features ###
- Add ability to cancel all orders for specific market [\#2125](https://github.com/rubykube/peatio/pull/2125)
- Move order submit to order\_processor and remove Ordering service [\#2147](https://github.com/rubykube/peatio/pull/2147)
- Add note to withdraw [\#2157](https://github.com/rubykube/peatio/pull/2157)
- Add filter by date in market/trades REST API call [\#2126](https://github.com/rubykube/peatio/pull/2126)
- Add optional fields for operations API [\#2140](https://github.com/rubykube/peatio/pull/2140)
- Benchmark tasks for Matching TradeExecution and OrderProcessing [\#2133](https://github.com/rubykube/peatio/pull/2133)
### Enhancements ###
- Remove Peatio.tech brand from admin panel [#2072](https://github.com/rubykube/peatio/pull/2072)
- Update application.yml.erb [#2098](https://github.com/rubykube/peatio/pull/2098)
- Get rid off grape\_strip gem [\#2116](https://github.com/rubykube/peatio/pull/2116)
- Avoid "message" in API controllers by overriding Grape::AllowBlankValidator [\#2094](https://github.com/rubykube/peatio/pull/2094)
- Upgrade Ruby on Rails to 5.0 [\#2095](https://github.com/rubykube/peatio/pull/2095)
- Upgrade Ruby on Rails to 5.2 [\#2146](https://github.com/rubykube/peatio/pull/2146)
- Update setup-ubuntu.md [\#2103](https://github.com/rubykube/peatio/pull/2103)
- Add missing paginations for deposit & withdraw on admin panel [\#2156](https://github.com/rubykube/peatio/pull/2156)
- Upgrade ruby to 2.6.2 [\#2160](https://github.com/rubykube/peatio/pull/2160)
- Skip withdrawal in case of insufficient balance on hot wallet [\#2178](https://github.com/rubykube/peatio/pull/2178)
### Fixes ###
- Fix release:travis rake task [\#2145](https://github.com/rubykube/peatio/pull/2145)
- Fix bin/gendocs [\#2150](https://github.com/rubykube/peatio/pull/2150)
- Limit number of returned data from ranger `global.update` [\#2153](https://github.com/rubykube/peatio/pull/2153)
- Rewrite callbacks for avoid using redirect\_to :back [\#2113](https://github.com/rubykube/peatio/pull/2113)
- Revert ability to deposit from admin panel [\#2164](https://github.com/rubykube/peatio/pull/2164)
- Rewrite callbacks for avoid using redirect\_to :back [\#2169](https://github.com/rubykube/peatio/pull/2169)

133
docs/releases/2.2.0.md Normal file
View File

@@ -0,0 +1,133 @@
## Peatio 2.2.0 (June 3, 2019) ##
### Overview ###
We are pleased to present Peatio Open Source 2.2.0.
This release concentrated on Plugable Coins API development new features and enhancements:
1. New admin roles integration.
2. Admin panel RBAC.
3. Daemons stability and performance improvements.
3. Foundation for third party trading engine integration.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- [#2168](https://github.com/rubykube/peatio/pull/2168): Plugable Coins API
This PR is gives ability gives ability to extend Peatio with new coins implementation.
Such a big architecture improvements usually brings breaking changes.
Core Peatio supports Ethereum, Bitcoin and Litecoin(as a plugin) blockchains.
It means that you need to build custom image if you want to integrate other coins.
For guide of how to build custom docker image check [documentation](../plugins.md).
For coin integration guide check **doc/integration.md** of appropriate coin e.g([litecoin](https://github.com/rubykube/peatio-litecoin/blob/master/docs/integration.md)).
You will find the list of approved coin plugins [here](../coins/plugins.md).
- [#2242](https://github.com/rubykube/peatio/pull/2242): Reorganization ruby and amqp workers.
Raw ruby daemons starting script was unified in the same way as we do for AMQP daemons.
So now to start ruby daemon you need to run the next command:
```bash
bundle exec ruby lib/daemons/daemons.rb daemon_name
```
- [#2241](https://github.com/rubykube/peatio/pull/2241): Major Market model rework.
This patch makes bunch of changes in Market model and related APIs, controllers and configuration.
Here is the full list of braking changes for more info check [PR](https://github.com/rubykube/peatio/pull/2241):
* Replace Market `enabled` with `state` and list new states (without
logic implementation)
* Rework public/market API response structure
* Rename Market API error name `market.market.doesnt_exist` -> `market.market.doesnt_exist_or_not_enabled`
* Add ability to disable all markets
* Remove precision equivalence validation (now amount and price precision could be different)
* Add precisions sum validation (amount + price precision < 12)
* Merge min_bid_amount & min_ask_amount to min_amount
* Update Market seeds
* Rename ask_precision -> amount_precision, bid_precision -> price_precision
* Rename min_ask_price -> min_price, max_bid_price -> max_price
* Rename ask_unit -> base_unit, bid_unit -> quote_unit
- [#2267](https://github.com/rubykube/peatio/pull/2267): Move slave book from amqp to ruby daemons.
This PR changes slave book daemon type from AMQP daemon to raw ruby one.
Now to start slave book you need to run `bundle exec ruby lib/daemons/daemons.rb slave_book`.
- [#2257](https://github.com/rubykube/peatio/pull/2257): Refactor blockchain daemon.
Now Blockchain daemon doesn't scaling and BLOCKCHAINS env variable.
Current version of Blockchain daemon starts separate thread per blockchain which works simultaneously and doesn't depend on each other.
So it doesn't need scaling to multiple process and BLOCKCHAINS env variable.
- [#2258](https://github.com/rubykube/peatio/pull/2258): Major trading engine and logic rework with precision, rounding and matching flow improvements.
Trading engine rework includes bunch of flow enhancements:
* Remove rounding on order creation
* Validate volume and price precision on order creation
* Return invalid_price_or_volume error in case of fractional part overflow
* Validate Market min_price, max_price and min_amount depending on amount and price precision
* Market amount_precision + price_precision < FUNDS_PRECISION = 12
* Set Market FEE_PRECISION to 4
* Round estimated funds on market order creation
* Rewrite Matching::Engine from scratch without recursion
* Update markets.yml.erb with new min_price, min_amount
### New Features ###
- Admin panel RBAC. New admin roles support [#2217](https://github.com/rubykube/peatio/pull/2217) ([chumaknadya](https://github.com/chumaknadya))
Now we support the next list of admin privileged roles:
* Super admin
* Admin
* Accountant
* Compliance
* Technical
* Support
For the list of permissions for each role check [PR](https://github.com/rubykube/peatio/pull/2217)
- AMQP messages for third party trading engine integration [\#2215](https://github.com/rubykube/peatio/pull/2215) ([ysv](https://github.com/ysv))
Our plan is to support third party trading engine, so we can replace all peatio trading daemons without breaking compatibility.
This PR adds functionality of publishing Order submit and cancel, Liability create events to RMQ.
- Add management API endpoint for listing trades [\#2182](https://github.com/rubykube/peatio/pull/2182) ([ymasiuk](https://github.com/ymasiuk))
- Change order 'state' to int for order\_processor [\#2205](https://github.com/rubykube/peatio/pull/2205) ([mnaichuk](https://github.com/mnaichuk))
- AMQP messages for third party trading engine integration [\#2215](https://github.com/rubykube/peatio/pull/2215) ([ysv](https://github.com/ysv))
- Use json format for logs [\#2232](https://github.com/rubykube/peatio/pull/2232) ([denisfd](https://github.com/denisfd))
- Retry withdraw on failure [\#2233](https://github.com/rubykube/peatio/pull/2233) ([shal](https://github.com/shal))
- Change: config/database.yml use port value from ENV [\#2254](https://github.com/rubykube/peatio/pull/2254) ([matass](https://github.com/matass))
- Add min\_confirmations field to Currency model entity [\#2276](https://github.com/rubykube/peatio/pull/2276) ([mnaichuk](https://github.com/mnaichuk))
- Add bitcoincash and ripple [\#2284](https://github.com/rubykube/peatio/pull/2286)([ymasiuk](https://github.com/ymasiuk))
### Enhancements ###
- Skip withdrawal in case of insufficient balance on hot wallet [\#2179](https://github.com/rubykube/peatio/pull/2179) ([mnaichuk](https://github.com/mnaichuk))
- Update RBAC roles [\#2237](https://github.com/rubykube/peatio/pull/2237) ([mnaichuk](https://github.com/mnaichuk))
- Add WS message for market order executed event [\#2208](https://github.com/rubykube/peatio/pull/2208) ([mnaichuk](https://github.com/mnaichuk))
- Replace Passgen gem with new password generator [\#2245](https://github.com/rubykube/peatio/pull/2245) ([mnaichuk](https://github.com/mnaichuk))
- Update Readme [\#2250](https://github.com/rubykube/peatio/pull/2250) ([liutenko](https://github.com/liutenko))
- Improve sentry-raven error reporting [\#2236](https://github.com/rubykube/peatio/pull/2236) ([mnaichuk](https://github.com/mnaichuk))
- Update logs in withdraw\_coin worker [\#2234](https://github.com/rubykube/peatio/pull/2234) ([denisfd](https://github.com/denisfd))
- Update ruby version and gems [\#2263](https://github.com/rubykube/peatio/pull/2263) ([mod](https://github.com/mod))
- Multi coin support for altcoins [\#2243](https://github.com/rubykube/peatio/pull/2243) ([Xicy](https://github.com/Xicy))
### Bug Fixes ###
- Remove JWT token from response payload [\#2265](https://github.com/rubykube/peatio/pull/2265) ([shal](https://github.com/shal))
- Remove http request for confirmations method [\#2262](https://github.com/rubykube/peatio/pull/2262) ([mnaichuk](https://github.com/mnaichuk))
- Reload blockchain from DB before sync [\#2269](https://github.com/rubykube/peatio/pull/2269) ([mnaichuk](https://github.com/mnaichuk))
- Fix bin/gendocs [\#2272](https://github.com/rubykube/peatio/pull/2272) ([mnaichuk](https://github.com/mnaichuk))
- Fix issue with rake task release.rake in travis [\#2275](https://github.com/rubykube/peatio/pull/2275) ([mnaichuk](https://github.com/mnaichuk))
- Fix GET /withdraws to include both fiat and crypto [\#2222](https://github.com/rubykube/peatio/pull/2222) ([msembinelli](https://github.com/msembinelli))
- Remove withdrawal attempts [\#2280](https://github.com/rubykube/peatio/pull/2280) ([mnaichuk](https://github.com/mnaichuk))
- Fix double spending issue on withdraw [\#2280](https://github.com/rubykube/peatio/pull/2280) ([mnaichuk](https://github.com/mnaichuk))

217
docs/releases/2.3.0.md Normal file
View File

@@ -0,0 +1,217 @@
## Peatio 2.3.0 (September 15, 2019) ##
### Overview ###
We are pleased to present Peatio Open Source 2.3.0.
This release concentrated on new Admin API module, new features and enhancements:
1. Refactoring to maker-taker fee model. Major Trade model rework.
2. Admin API module for tower.
3. Trading Fee Schedule based on Member group.
4. Introduce adjustments.
5. Beneficiaries model and fiat withdrawal.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- [#2278](https://github.com/rubykube/peatio/pull/2278): Market & Currency admin forms corrections & improvements
- Improve Market form validations and errors
- Ask/Bid fee -> Quote/Base currency fee
- Base/Quote unit -> Base/Quote currency
- Use number_field for decimals
- Id has already been taken -> #{base}, #{quote} market already exists
- Validate amount_precision instead of precisions sum
- Validate price_preciosion to be less than FUNDS_PRECISION
- Validate amount_precision to be less than FUNDS_PRECISION - price_precision
- Update deposit table columns
- Validate code instead of id in Currency
- Define convention for organizing Ruby On Rails Models
- Use 'withdrawal' instead of 'withdraw' everywhere
- [#2292](https://github.com/rubykube/peatio/pull/2292): Switch to maker-taker fee model. Major Trade model rework
This patch replaces side-related (buy or sell) with maker-taker fee model. Its basic structure gives a fee discount to market makers providing liquidity (the makers); and charges higher fee to customers who take liquidity out of the market (the takers). Fee could be configured per market.
Next changes were produced by switching to maker-taker fee model:
- Replace `ask_fee` and `bid_fee` with `maker_fee` and `taker_fee` in Market model;
- Replace `fee` with `maker_fee` and `taker_fee` in Order model;
- Update Entities for Market and Trade models in user API, Trade model in management API;
- Update Trade Accounting with maker/taker_fee;
- Update Trade_executor and Matching_engine with new Trade model;
- Update Market seeds;
- Specs for maker/taker_fee;
Trade model rework consist of next changes:
- Update Trade model structure:
- ask_id -> maker_order_id;
- bid_id -> taker_order_id;
- ask_member_id -> maker_id;
- bid_member_id -> taker_id;
- volume -> amount;
- funds -> total;
- drop trend;
### New Features ###
- [#2264](https://github.com/rubykube/peatio/pull/2264): Admin API module for tower ([mod](https://github.com/mod))
- Feature admin panel api for:
- Orders
- Blockchains
- Currencies
- Markets
- Wallets
- Deposits
- Withdraws
- Trades
- Operations
- Members
Unify API doc files structure and naming.
- [#2321](https://github.com/rubykube/peatio/pull/2321): Trading Fee Schedule based on Member group ([ysv](https://github.com/ysv))
- Add FeeSchedule module;
- Add FeeSchedule::TradingFee model;
- FeeSchedule::TradingFee record selected with the next priorities:
- both group and market_id match
- group match
- market_id match
- both group and market_id are nil
- default (zero fees)
- Add Group member column;
- Remove maker/taker_fee from Market model;
- Add custom validator class PrecisionValidator for validate precisions for Order, TradingFee, Market models;
- FeeSchedule::TradingFees seeding via rake task;
- [#2310](https://github.com/rubykube/peatio/pull/2310): Use Vault transit engine for storing Wallet & PaymentAddress sensitive data ([dnfd](https://github.com/dnfd))
- [#2325](https://github.com/rubykube/peatio/pull/2325): Integrate ability to create accounting Adjustments ([dnfd](https://github.com/dnfd))
- Add Adjustment model;
- Adjustement has pending, accepted and rejected states;
- Only on accepted state creates operations;
- Add API for get, create and accept/reject adjustments;
- Adjustment creates a pair with asset and liabilty || revenue || expense;
- Update user balance in case of creation liability after accepting adjustment;
Co-authored-by: mnaichuk <mnaichuk@heliostech.fr>
Co-authored-by: dnfd <dfedorchenko@heliostech.fr>
- [#2347](https://github.com/rubykube/peatio/pull/2347) Beneficiaries model with ability to manage via user API ([mod](https://github.com/mod))
Add Beneficiary model which can store both fiat crypto beneficiary data. Custom beneficiary fields like country, account_number, bank_swift_code are stored in JSON format. Also beneficiary contains name, description & currency_id in string format.
On beneficiary creation pin generated and saved in DB user needs to activate beneficiary with pin sent by email. Create & update actions are published to RabbitMQ by Event API.
There are 3 states of beneficiary:
- pending - requires activation with pin;
- active - activated by user and can be used for withdrawal;
- achieved - equal to removed except fact that admin can read it.
Beneficiary account API consists of 5 endpoints:
- GET /beneficiaries - get paginated list of beneficiaries for user;
- GET /beneficiaries/:id - get single beneficiary by id;
- POST /beneficiaries - create beneficiary for user;
- PATH /beneficiaries/:id/activate - activate beneficiary with pin;
- DELETE /beneficiaries/:id - delete beneficiary (actually change state to archived).
Co-authored-by: ysv <ysavchuk@heliostech.fr>
Co-authored-by: mod <lbellet@heliostech.fr>
- [#2355](https://github.com/rubykube/peatio/pull/2355): Integrate ability to withdraw both fiat & crypto with Beneficiary model ([ysv](https://github.com/ysv))
Since we can store Beneficiaries in peatio starting from #2347 now we can
implement user withdraw API for both fiat & crypto currencies. Itmeans that in
this patch we have replaced POST accounts/withdraw `rid` param with
`beneficiary_id`. This change gives ability to use active beneficiaries for
both fiat & crypto withdrawals.
`Beneficiary` is now exposed in Admin API as field of `Withdraw` so admin can
validate it directly.
`beneficiary_id` foreign key was added to `Withdraw` model so now it has
optional `belongs_to` association with `Beneficiary`.
Also this patch improves `Withdraw` `sum` & `amount` precision logic. Instead
of rounding attributes on creation now attributes precision is validated on
`Withdraw` creation.
This patch also adds additional validation for Beneficiary data attribute
### Enhancements ###
- Add RevShare model. Add state to Trade [\#2283](https://github.com/rubykube/peatio/pull/2283) ([ysv](https://github.com/ysv))
- Add GET API for Operations and Members [\#2285](https://github.com/rubykube/peatio/pull/2285) ([dnfd](https://github.com/dnfd))
- Update peatio-ripple gem version [\#2298](https://github.com/rubykube/peatio/pull/2298) ([mnaichuk](https://github.com/mnaichuk))
- Update peatio-ripple gem version [\#2306](https://github.com/rubykube/peatio/pull/2306) ([ysv](https://github.com/ysv))
- Update API doc files structure and naming [\#2305](https://github.com/rubykube/peatio/pull/2305) ([ysv](https://github.com/ysv))
- Update peatio-ripple gem version [\#2304](https://github.com/rubykube/peatio/pull/2304) ([ysv](https://github.com/ysv))
- Add parity wallet gataway and use it instead of peth. Deprecate peth [\#2295](https://github.com/rubykube/peatio/pull/2295) ([streetcrypto7](https://github.com/streetcrypto7))
- Update management/transfers [\#2307](https://github.com/rubykube/peatio/pull/2307) ([dnfd](https://github.com/dnfd))
- Drop step from blockchain model [\#2282](https://github.com/rubykube/peatio/pull/2282) ([shal](https://github.com/shal))
- Change run Peatio::Application to Rails.application in config.ru [\#2316](https://github.com/rubykube/peatio/pull/2316) ([ysv](https://github.com/ysv))
- Upgrade Transfer model. Add gross Revenue account [\#2301](https://github.com/rubykube/peatio/pull/2301) ([ysv](https://github.com/ysv))
- Prepare management API for Revenue Share [\#2293](https://github.com/rubykube/peatio/pull/2293) ([shal](https://github.com/shal))
- Update Admin API [\#2317](https://github.com/rubykube/peatio/pull/2317) ([dnfd](https://github.com/dnfd))
- Feature: add gem for support dash [\#2338](https://github.com/rubykube/peatio/pull/2338) ([ymasiuk](https://github.com/ymasiuk))
- Update API [\#2336](https://github.com/rubykube/peatio/pull/2336) ([dnfd](https://github.com/dnfd))
- Use Faker::Blockchain::Bitcoin instead of Faker::Bitcoin [\#2343](https://github.com/rubykube/peatio/pull/2343) ([ysv](https://github.com/ysv))
- Update specs for swagger [\#2340](https://github.com/rubykube/peatio/pull/2340) ([dnfd](https://github.com/dnfd))
- Add endpoint to list all blockchain clients & provide access to disabled markets in Admin API [\#2339](https://github.com/rubykube/peatio/pull/2339) ([dnfd](https://github.com/dnfd))
- Remove uid length limit in members table [\#2346](https://github.com/rubykube/peatio/pull/2346) ([mnaichuk](https://github.com/mnaichuk))
- Add Admin and Management API for TradingFees [\#2334](https://github.com/rubykube/peatio/pull/2334) ([mnaichuk](https://github.com/mnaichuk))
- Minor Wallet Admin API fixes & improvements. Drop parent & nsig from Wallet [\#2348](https://github.com/rubykube/peatio/pull/2348) ([dnfd](https://github.com/dnfd))
- Add uid, email field for withdrawal and deposits admin entities [\#2350](https://github.com/rubykube/peatio/pull/2350) ([mnaichuk](https://github.com/mnaichuk))
- Add public endpoint for trading\_fees [\#2353](https://github.com/rubykube/peatio/pull/2353) ([mnaichuk](https://github.com/mnaichuk))
- Add actions endpoints for Withdraw and Deposit Admin API [\#2351](https://github.com/rubykube/peatio/pull/2351) ([dnfd](https://github.com/dnfd))
- Minor Transfer table updates [\#2356](https://github.com/rubykube/peatio/pull/2356) ([mnaichuk](https://github.com/mnaichuk))
- Add endpoint to select adjustment by ID [\#2354](https://github.com/rubykube/peatio/pull/2354) ([mnaichuk](https://github.com/mnaichuk))
- Add endpoint for create fiat deposit [\#2357](https://github.com/rubykube/peatio/pull/2357) ([chumaknadya](https://github.com/chumaknadya))
- Add ability to change markets precision in Admin API [\#2361](https://github.com/rubykube/peatio/pull/2361) ([ysv](https://github.com/ysv))
- Use grape entity for exposing & documenting market ticker [\#2365](https://github.com/rubykube/peatio/pull/2365) ([ysv](https://github.com/ysv))
- Add details about fees in trade API [\#2363](https://github.com/rubykube/peatio/pull/2363) ([dnfd](https://github.com/dnfd))
- Validate accounting on Transfer & Adjustment creation. Create account on fly if does not exist [\#2370](https://github.com/rubykube/peatio/pull/2370) ([mnaichuk](https://github.com/mnaichuk))
- Add endpoint to get currency by code to management API ([#2372](https://github.com/openware/peatio/issues/2372))
- Reraise errors in #submit and #cancel methods ([#2375](https://github.com/openware/peatio/issues/2375))
- OrderProcessor must process order cancel after TradeExecutor ([#2371](https://github.com/openware/peatio/issues/2371))
- Add visible, deposit_enabled, withdrawal_enabled columns to Currency ([#2374](https://github.com/openware/peatio/issues/2374))
- Update README.md
- Update CI to build images with git sha for branches matching {fix,integration}/*
- Update update sassc and ffi
- Update websocket API documentation for peatio 2.4 ([#2505](https://github.com/openware/peatio/issues/2505))
- Update irix and peatio-bitgo versions ([#2533](https://github.com/openware/peatio/issues/2533))
- Update export task with data field for market ([#2513](https://github.com/openware/peatio/issues/2513))
- Update irix version ([#2506](https://github.com/openware/peatio/issues/2506))
- Update peatio plugins ([#2504](https://github.com/openware/peatio/issues/2504))
- Update to Rails 5.2.4 ([#2466](https://github.com/openware/peatio/issues/2466))
- Update Peatio API documentation ([#2477](https://github.com/openware/peatio/issues/2477))
- Update roadmap.md
- Update Order model for compatibility with Finex ([#2440](https://github.com/openware/peatio/issues/2440))
- Update gem versions ([#2414](https://github.com/openware/peatio/issues/2414))
- Update ruby to 2.6.5 for security reasons ([#2386](https://github.com/openware/peatio/issues/2386))
- Support beneficiary_id in management API create withdraw ([#2378](https://github.com/openware/peatio/issues/2378))
- Support beneficiary_id in management API create withdraw ([#2378](https://github.com/openware/peatio/issues/2378))
- Tweak public-markets endpoint ([#2395](https://github.com/openware/peatio/issues/2395))
### Bug Fixes ###
- Update gendocs script [\#2300](https://github.com/rubykube/peatio/pull/2300) ([dnfd](https://github.com/dnfd))
- Update gem versions to reduce vulnerabilities [\#2318](https://github.com/rubykube/peatio/pull/2318) ([snyk-bot](https://github.com/snyk-bot))
- Fail ethereum withdrawal in case of fail status in blockchain [\#2302](https://github.com/rubykube/peatio/pull/2302) ([mnaichuk](https://github.com/mnaichuk))
- Don't use validations for updating database in migrations [\#2324](https://github.com/rubykube/peatio/pull/2324) ([mnaichuk](https://github.com/mnaichuk))
- Add ability to bump & tag stable branches [\#2328](https://github.com/rubykube/peatio/pull/2328) ([mnaichuk](https://github.com/mnaichuk))
- Fail ethereum withdrawal in case of fail status in blockchain [\#2327](https://github.com/rubykube/peatio/pull/2327) ([mnaichuk](https://github.com/mnaichuk))
- Rewrite validation for buy and sell order in trade\_executor [\#2335](https://github.com/rubykube/peatio/pull/2335) ([mnaichuk](https://github.com/mnaichuk))
- Remove jq package from gendocs [\#2333](https://github.com/rubykube/peatio/pull/2333) ([dnfd](https://github.com/dnfd))
- Add missing -y for jq install in bin/gendocs [\#2332](https://github.com/rubykube/peatio/pull/2332) ([mnaichuk](https://github.com/mnaichuk))
- Use update\_attribute in migrations for skipping validations [\#2331](https://github.com/rubykube/peatio/pull/2331) ([mnaichuk](https://github.com/mnaichuk))
- Add email to withdraw & deposit event\_api payloads [\#2349](https://github.com/rubykube/peatio/pull/2349) ([shal](https://github.com/shal))
- Minor Admin fixes for Blockchain, Order, Trade, Currency [\#2352](https://github.com/rubykube/peatio/pull/2352) ([chumaknadya](https://github.com/chumaknadya))
- Fix 422 response on successful withdraw action [\#2358](https://github.com/rubykube/peatio/pull/2358) ([dnfd](https://github.com/dnfd))
- Increase trading fees maker & taker precision to 6 digits [\#2360](https://github.com/rubykube/peatio/pull/2360) ([ysv](https://github.com/ysv))
- Crash daemons on Mysql connection error [\#2367](https://github.com/rubykube/peatio/pull/2367) ([dnfd](https://github.com/dnfd))
- Do not log full backtrace on order creation ([#2368](https://github.com/openware/peatio/issues/2368))

122
docs/releases/2.4.0.md Normal file
View File

@@ -0,0 +1,122 @@
## Peatio 2.4.0 (March 23, 2020) ##
### Overview ###
We are pleased to present Peatio Open Source 2.4.0.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- Remove deprecated amqp daemons [\#2451](https://github.com/openware/peatio/pull/2451) ([mnaichuk](https://github.com/mnaichuk))
Deleted workers:
* Pusher Market
* Pusher Member
Moved EventApi and AMQP modules to lib folder.
- Record Trades and K-lines to InfluxDB [\#2441](https://github.com/openware/peatio/pull/2441) ([mnaichuk](https://github.com/mnaichuk))
* Add InfluxDB client;
* Add new AMQP daemon InfluxDB writer;
* Rewrite Public Trade endpoint to return trades from influx;
* Rewrite Public K-line endpoint to return k-lines from influx;
* Rewrite k-line daemon;
* Rewrite KlineService;
* Update backend.yml;
* Update drone.yml;
* Update ./bin/setup;
* Update daemons.god;
- Add CronJob Daemon for K-lines and Tickers [\#2485](https://github.com/openware/peatio/pull/2485) ([mnaichuk](https://github.com/mnaichuk))
- Add ability to read tickers from influx [\#2480](https://github.com/openware/peatio/pull/2480) ([mnaichuk](https://github.com/mnaichuk))
* Add Cronjob daemon with Jobs::Cron::KLine, Jobs::Cron::Ticker jobs;
* Remove MarketTicker, K, SlaveBook and GlobalState daemons;
* Remove Global.rb;
* Add TickersService and KLineSerivce;
* Update API and WS API with new services.
### New Features ###
- Add Peatio Upstream worker. Add Opendax Upstream [\#2458](https://github.com/openware/peatio/pull/2458) ([mnaichuk](https://github.com/mnaichuk))
* Introduce Upstream Worker;
* Add encrypted data field to market model;
* Upstream will initialize from market data:
- {"upstream"=>{"driver"=>"opendax", "target"=>"btcusdt", "rest"=>"https://url", "websocket"=>"wss://url"}}
* Add Upstream::Peatio::Opendax class;
- Incremental order-book [\#2400](https://github.com/openware/peatio/pull/2400) ([calj](https://github.com/calj))
This stream sends a snapshot of the order-book at the subscription time, then it sends increments. Volumes information in increments replace the previous values. If the volume is zero the price point should be removed from the order-book. Documentation for [incremental order-book](https://github.com/openware/peatio/blob/master/docs/api/websocket_api.md#order-book)
- Add ability to create deposits and confirm withdrawals through Webhooks. [\#2460](https://github.com/openware/peatio/pull/2460) ([mnaichuk](https://github.com/mnaichuk))
Add Peatio Bitgo plugin. Documentation for [bitgo plugin](https://github.com/openware/peatio-contrib/tree/master/peatio-bitgo/docs)
Add Peatio public Webhook endpoint for deposit and withdraw detection through Bitgo events.
### Enhancements ###
- Replace legacy authentication with jwt-rack [\#2450](https://github.com/openware/peatio/pull/2450) ([ysv](https://github.com/ysv))
- Add default value for data market field [\#2553](https://github.com/openware/peatio/pull/2553) ([mnaichuk](https://github.com/mnaichuk))
- Use scheduling in blockchain daemon to reflect config changes in DB [\#2552](https://github.com/openware/peatio/pull/2552) ([ysv](https://github.com/ysv))
- Add docs about engines [\#2546](https://github.com/openware/peatio/pull/2546) ([dnfd](https://github.com/dnfd))
- Update gems dependencies [\#2549](https://github.com/openware/peatio/pull/2549) ([mnaichuk](https://github.com/mnaichuk))
- Delete encrypt for market data. Update upstream daemon [\#2543](https://github.com/openware/peatio/pull/2543) ([mnaichuk](https://github.com/mnaichuk))
- Add manager role [\#2540](https://github.com/openware/peatio/pull/2540) ([mnaichuk](https://github.com/mnaichuk))
- Add admin api for engines [\#2538](https://github.com/openware/peatio/pull/2538) ([mnaichuk](https://github.com/mnaichuk))
- Update peatio-core version [\#2536](https://github.com/openware/peatio/pull/2536) ([mnaichuk](https://github.com/mnaichuk))
- Update column type for data engines [\#2534](https://github.com/openware/peatio/pull/2534) ([mnaichuk](https://github.com/mnaichuk))
- Feature: add POST admin/blockchain/process\_block [\#2526](https://github.com/openware/peatio/pull/2526) ([ec](https://github.com/ec))
- Enhancement: Improve deposit model. Add ability to collect through api [\#2510](https://github.com/openware/peatio/pull/2510) ([mnaichuk](https://github.com/mnaichuk))
- Websocket documentation for peatio 2.4 [\#2505](https://github.com/openware/peatio/pull/2505) ([calj](https://github.com/calj))
- Fix: Ability to save wallet secret on update [\#2501](https://github.com/openware/peatio/pull/2501) ([chumaknadya](https://github.com/chumaknadya))
- Update irix and peatio-bitgo versions [\#2532](https://github.com/openware/peatio/pull/2532) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Include post\_only order in market/depth [\#2531](https://github.com/openware/peatio/pull/2531) ([dnfd](https://github.com/dnfd))
- Remove old helpers [\#2528](https://github.com/openware/peatio/pull/2528) ([mnaichuk](https://github.com/mnaichuk))
- Return wallet balance in admin api [\#2522](https://github.com/openware/peatio/pull/2522) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Alive check for a blockchain node to get the latest block [\#2521](https://github.com/openware/peatio/pull/2521) ([chumaknadya](https://github.com/chumaknadya))
- Enhancement: Add ability to fail withdraw from skipped state [\#2519](https://github.com/openware/peatio/pull/2519) ([chumaknadya](https://github.com/chumaknadya))
- Feature: Expose deposit address && beneficiaries for admin endpoints [\#2518](https://github.com/openware/peatio/pull/2518) ([chumaknadya](https://github.com/chumaknadya))
- Remove LOCKING\_BUFFER\_FACTOR from buy market order [\#2509](https://github.com/openware/peatio/pull/2509) ([mnaichuk](https://github.com/mnaichuk))
- Add feature to search currency by code or name in /public/currencies [\#2516](https://github.com/openware/peatio/pull/2516) ([ysv](https://github.com/ysv))
- Enhancement: Add Kaigara installation to the Dockerfile [\#2514](https://github.com/openware/peatio/pull/2514) ([vshatravenko](https://github.com/vshatravenko))
- Update export task with data field for market [\#2513](https://github.com/openware/peatio/pull/2513) ([mnaichuk](https://github.com/mnaichuk))
- Update peatio plugins [\#2503](https://github.com/openware/peatio/pull/2503) ([mnaichuk](https://github.com/mnaichuk))
- Update websocket API documentation for peatio 2.4 [\#2502](https://github.com/openware/peatio/pull/2502) ([calj](https://github.com/calj))
- Enhancement: Improve deposits, withdrawals and transactions filters [\#2492](https://github.com/openware/peatio/pull/2492) ([mnaichuk](https://github.com/mnaichuk))
- Redeploy on master.devkube.com [\#2491](https://github.com/openware/peatio/pull/2491) ([dpatsora](https://github.com/dpatsora))
- Features and improvements pack [\#2490](https://github.com/openware/peatio/pull/2490) ([akulakovaa](https://github.com/akulakovaa))
- Setup redeploy on devkube [\#2489](https://github.com/openware/peatio/pull/2489) ([dpatsora](https://github.com/dpatsora))
- Feature: add POST management/currencies/list API endpoint [\#2487](https://github.com/openware/peatio/pull/2487) ([ec](https://github.com/ec))
- Add Trading docs [\#2478](https://github.com/openware/peatio/pull/2478) ([mnaichuk](https://github.com/mnaichuk))
- Update Peatio API documentation [\#2477](https://github.com/openware/peatio/pull/2477) ([mnaichuk](https://github.com/mnaichuk))
- Improve API filtering for order history [\#2476](https://github.com/openware/peatio/pull/2476) ([mnaichuk](https://github.com/mnaichuk))
- Prepare doc for Peatio v2.4 migration [\#2475](https://github.com/openware/peatio/pull/2475) ([dpatsora](https://github.com/dpatsora))
- Expose UUID [\#2473](https://github.com/openware/peatio/pull/2473) ([dnfd](https://github.com/dnfd))
- Enhancement: Delete total header from admin API endpoints [\#2468](https://github.com/openware/peatio/pull/2468) ([chumaknadya](https://github.com/chumaknadya))
- Update to Rails 5.2.4 [\#2466](https://github.com/openware/peatio/pull/2466) ([mod](https://github.com/mod))
- Enhancement: Add validation for trading fees, blockchains, transfers [\#2464](https://github.com/openware/peatio/pull/2464) ([chumaknadya](https://github.com/chumaknadya))
- Add filters by deposit/withdraw states [\#2463](https://github.com/openware/peatio/pull/2463) ([chumaknadya](https://github.com/chumaknadya))
- Add finex as third party engine support. Add to\_reject withdrawal state. Add maker role [\#2459](https://github.com/openware/peatio/pull/2459) ([mnaichuk](https://github.com/mnaichuk))
### Bug Fixes ###
- Skip pending ERC-20 transaction in blockchain daemon [\#2658](https://github.com/openware/peatio/pull/2658) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Avoid to use join in admin API for tables with a large amount of data. Change Kaminari usage in pagination [\#2602](https://github.com/openware/peatio/pull/2602)
- Fix: Remove nested SQL transactions in blockchain daemon. Update deposit model [\#2548](https://github.com/openware/peatio/pull/2548) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Update UID and GID to the app user for all project files [\#2499](https://github.com/openware/peatio/pull/2499) ([apaulb](https://github.com/apaulb))
- Fix file permissions [\#2496](https://github.com/openware/peatio/pull/2496) ([apaulb](https://github.com/apaulb))
- Fix: Add docs && changelog generation on master branch [\#2515](https://github.com/openware/peatio/pull/2515) ([chumaknadya](https://github.com/chumaknadya))
- Fix: add ability to cancel order by uuid [\#2508](https://github.com/openware/peatio/pull/2508) ([mikoim](https://github.com/mikoim))
- Fix: Add created\_at to transaction entity [\#2498](https://github.com/openware/peatio/pull/2498) ([chumaknadya](https://github.com/chumaknadya))
- \[Snyk\] Fix for 1 vulnerabilities [\#2494](https://github.com/openware/peatio/pull/2494) ([snyk-bot](https://github.com/snyk-bot))
- Fix: Clean rails built in warnings [\#2483](https://github.com/openware/peatio/pull/2483) ([mnaichuk](https://github.com/mnaichuk))
- Fix ./bin/setup [\#2482](https://github.com/openware/peatio/pull/2482) ([akulakovaa](https://github.com/akulakovaa))
- Fix: add ability to search order by uuid [\#2481](https://github.com/openware/peatio/pull/2481) ([akulakovaa](https://github.com/akulakovaa))
- Initialize Blockchain and Wallet adapters in service creation. Updat… [\#2474](https://github.com/openware/peatio/pull/2474) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Collect deposits after sql transaction [\#2471](https://github.com/openware/peatio/pull/2471) ([mnaichuk](https://github.com/mnaichuk))
- Publish events to specific exchange [\#2470](https://github.com/openware/peatio/pull/2470) ([dnfd](https://github.com/dnfd))
- Fix: Change beneficiary address validation [\#2462](https://github.com/openware/peatio/pull/2462) ([chumaknadya](https://github.com/chumaknadya))
- Fix: Add report exception to screen for OrderProcessor initialize [\#2453](https://github.com/openware/peatio/pull/2453) ([mnaichuk](https://github.com/mnaichuk))

115
docs/releases/2.5.0.md Normal file
View File

@@ -0,0 +1,115 @@
## Peatio 2.5.0 (August 7, 2020) ##
### Overview ###
We are pleased to present Peatio Open Source 2.5.0.
This release notes is must-read for migrating from older versions.
### Breaking changes ###
- Rewrite deposit collection flow [\#2636](https://github.com/openware/peatio/pull/2636) ([mnaichuk](https://github.com/mnaichuk))
* Remove amqp publish and add new deposit state
* Remove amqp deposit workers (deposit_collection and deposit_collections_fees daemons)
* Introduce SQL based deposit daemon
* Add deposit collection flow documentation
Documentation for [new deposit collection flow](https://github.com/openware/peatio/blob/master/docs/peatio/deposits_flow.md)
- Remove old Peatio admin panel [\#2523](https://github.com/openware/peatio/pull/2523) ([mnaichuk](https://github.com/mnaichuk))
### New Features ###
- Feature: PnL calculation for traders ([calj](https://github.com/calj))
* Uses deposits, withdrawals, trades, adjustments and simple transfers
* Supports multi-level conversions
Increase time precision to milliseconds for deposits, withdrawals, trades and adjustments
Documentation for [PNL calculation](https://github.com/openware/peatio/blob/master/docs/peatio/pnl_calculation.md)
- Move data from main database to archive database [\#2632](https://github.com/openware/peatio/pull/2632) ([mnaichuk](https://github.com/mnaichuk))
* Add stored procedure execution from rake task
* Delete old cancelled orders without trades
* Add copy orders to the archive database
* Close orders older than MAX_AGE
Documentation list:
1. [Order close job](https://github.com/openware/peatio/blob/master/docs/tasks/order_close.md)
2. [Order archive job](https://github.com/openware/peatio/blob/master/docs/tasks/order_archive.md)
3. [Order liabilities compact job](https://github.com/openware/peatio/blob/master/docs/tasks/order_liabilities_compact.md)
- AML integration [\#2589](https://github.com/openware/peatio/pull/2589) ([mnaichuk](https://github.com/mnaichuk))
* Add AMLplugin system
* Add AML functions for Beneficiary model
* Store deposits source addresses
* Add admin beneficiary api
* Add refund model
- Add peatio electrum gem [\#2554](https://github.com/openware/peatio/pull/2554) ([calj](https://github.com/calj))
- Add wallet balances. Add cron job for wallet balances update ([mnaichuk](https://github.com/mnaichuk))
Add CronJob for periodic call and save platform wallets balances to the DB. Balances are updated every minute.
### Enhancements ###
- Add possibility to import and export Operation::Accounts [\#2721](https://github.com/openware/peatio/pull/2721) ([dpatsora](https://github.com/dpatsora))
- Add export:configs Rake task \(\#2693\) [\#2706](https://github.com/openware/peatio/pull/2706) ([mnaichuk](https://github.com/mnaichuk))
- Optimize PnL main query [\#2688](https://github.com/openware/peatio/pull/2688) ([calj](https://github.com/calj))
- Trigger custom image build [\#2695](https://github.com/openware/peatio/pull/2695) ([josadcha](https://github.com/josadcha))
- Update CI to build images for branches matching {fix,integration}/\* [\#2677](https://github.com/openware/peatio/pull/2677) ([calj](https://github.com/calj))
- Update sassc & ffi dependencies [\#2673](https://github.com/openware/peatio/pull/2673) ([calj](https://github.com/calj))
- Add from\_addresses on deposit creation [\#2657](https://github.com/openware/peatio/pull/2657) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: Filter trade by type && expose received_amount ([chumaknadya](https://github.com/chumaknadya))
- Accounting: add member_id in platform revenues [\#2607](https://github.com/openware/peatio/pull/2607) ([calj](https://github.com/calj)
- Add jobs table [\#2649](https://github.com/openware/peatio/pull/2649) ([mnaichuk](https://github.com/mnaichuk))
- Add rake task for distribution [\#2631](https://github.com/openware/peatio/pull/2631) ([mnaichuk](https://github.com/mnaichuk))
- Expose maker & taker fee for order entity (#2627) ([vpetrusenko](https://github.com/vpetrusenko))
- Add caching for the most used public endpoints [\#2625](https://github.com/openware/peatio/pull/2625) ([mnaichuk](https://github.com/mnaichuk))
- Add to Currency model description, homepage and price [\#2601](https://github.com/openware/peatio/pull/2601) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Add ability to skip deposit collection on hot wallet [\#2613](https://github.com/openware/peatio/pull/2613) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: add pagination to POST management/accounts/balances [\#2603](https://github.com/openware/peatio/pull/2603) ([ec](https://github.com/ec))
- Bump peatio-electrum plugin to 2.6.1 [\#2592](https://github.com/openware/peatio/pull/2592) ([calj](https://github.com/calj))
- \[Snyk\] Security upgrade kaminari from 1.1.1 to 1.2.1 [\#2586](https://github.com/openware/peatio/pull/2586) ([snyk-bot](https://github.com/snyk-bot))
- Feature: Add ability to resend beneficiary pin [\#2591](https://github.com/openware/peatio/pull/2591) ([dpatsora](https://github.com/dpatsora))
- Enhancement: add management api to retrieve non-zero balances [\#2570](https://github.com/openware/peatio/pull/2570) ([ec](https://github.com/ec))
- Add ability to set user rate limit [\#2580](https://github.com/openware/peatio/pull/2580) ([Kohelbekker](https://github.com/Kohelbekker))
- Change Influxdb configuration names [\#2573](https://github.com/openware/peatio/pull/2573) ([mnaichuk](https://github.com/mnaichuk))
- \[Snyk\] Fix for 5 vulnerabilities [\#2563](https://github.com/openware/peatio/pull/2563) ([snyk-bot](https://github.com/snyk-bot))
- Improve market states for api [\#2572](https://github.com/openware/peatio/pull/2572) ([mnaichuk](https://github.com/mnaichuk))
- Add export rake task for engines [\#2571](https://github.com/openware/peatio/pull/2571) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Add filters for currencies, markets and wallets [\#2567](https://github.com/openware/peatio/pull/2567) ([dpatsora](https://github.com/dpatsora))
- Improve orders and trades filtes. Add data field in engine admin API [\#2565](https://github.com/openware/peatio/pull/2565) ([mnaichuk](https://github.com/mnaichuk))
- Update irix version [\#2561](https://github.com/openware/peatio/pull/2561) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Add Management API for beneficiaries [\#2559](https://github.com/openware/peatio/pull/2559) ([chumaknadya](https://github.com/chumaknadya))
- Misc improvements [\#2556](https://github.com/openware/peatio/pull/2556) ([calj](https://github.com/calj))
- Delete encrypt for market data. Update upstream daemon [\#2543](https://github.com/openware/peatio/pull/2543) ([mnaichuk](https://github.com/mnaichuk))
- Feature: Add user portfolio API module [\#2537](https://github.com/openware/peatio/pull/2537) ([mnaichuk](https://github.com/mnaichuk))
### Bug Fixes ###
- Update peatio-bitgo version. Change rid length for withdraw [\#2668](https://github.com/openware/peatio/pull/2668) ([mnaichuk](https://github.com/mnaichuk))
- Fix wallet balance parse in the daemons [\#2666](https://github.com/openware/peatio/pull/2666) ([mnaichuk](https://github.com/mnaichuk))
- Skip pending ERC-20 transaction in blockchain daemon [\#2659](https://github.com/openware/peatio/pull/2659) ([mnaichuk](https://github.com/mnaichuk))
- Remove inqury from TradingFee model ([mnaichuk](https://github.com/mnaichuk))
- Fix format function in TickersJob ([mnaichuk](https://github.com/mnaichuk))
- Remove date parsing in api/v2/public/version [\#2623](https://github.com/openware/peatio/pull/2623) ([calj](https://github.com/calj))
- Fix secret replace in deposit collection [\#2620](https://github.com/openware/peatio/pull/2620) ([mnaichuk](https://github.com/mnaichuk))
- Update configuration for database pool [\#2619](https://github.com/openware/peatio/pull/2619) ([mnaichuk](https://github.com/mnaichuk))
- Add symbolize keys to WalletService init. Update wallet templates [\#2616](https://github.com/openware/peatio/pull/2616) ([mnaichuk](https://github.com/mnaichuk))
- Fix versionning generation in CI [\#2604](https://github.com/openware/peatio/pull/2604) ([calj](https://github.com/calj))
- Fix: Bitgo address generation [\#2608](https://github.com/openware/peatio/pull/2608) ([chumaknadya](https://github.com/chumaknadya))
- Fix: Update error handling for trading\_fee api [\#2595](https://github.com/openware/peatio/pull/2595) ([mnaichuk](https://github.com/mnaichuk))
- Do not expose engine data in admin api [\#2584](https://github.com/openware/peatio/pull/2584) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Avoid to use join in admin API for tables with a large amount of data. Change Kaminari usage in pagination [\#2602](https://github.com/openware/peatio/pull/2602) ([mnaichuk](https://github.com/mnaichuk))
- Fix market migration with existing data [\#2555](https://github.com/openware/peatio/pull/2555) ([mnaichuk](https://github.com/mnaichuk))

155
docs/releases/2.6.0.md Normal file
View File

@@ -0,0 +1,155 @@
## Peatio 2.6.0 (December 11, 2020) ##
### Overview ###
We are pleased to present Peatio Open Source 2.6.0.
This release concentrated on changes for user deposit addresses generation, new wallet clients, platform reliability, and security updates:
1. Unify deposit addresses for ETH & ERC20 tokens.
2. Global Withdraw Limits.
3. Implement adaptive gas_price setting.
4. Opendax wallet client support.
5. Yaml based admin and user permissions.
6. PostgreSQL and MariaDB support.
This release note is a must-read for migrating from older versions.
### Breaking changes ###
- Global Withdraw Limits [\#2670](https://github.com/openware/peatio/pull/2670) ([mnaichuk](https://github.com/mnaichuk))
Introduce the admin's ability to set global withdrawal limits in one currency (the platform global currency) for users.
Application of specific limits, depending on user KYC level and group.
Time limits control for one day or one month period.
* Add admin and public API modules for withdrawal limits.
* Add user endpoint for withdrawal sums for each period.
- Feature: Implement adaptive gas\_price setting [\#2684](https://github.com/openware/peatio/pull/2684) ([mnaichuk](https://github.com/mnaichuk))
Add the option "gas_price" to a currency with those possible values: `standard`, `safelow`, `fast`. By default, peatio will use the `standard` option. Make sure to change eth base currencies to those possible values.
- Feature: Unify deposit addresses for ETH & ERC20 tokens [\#2575](https://github.com/openware/peatio/pull/2575) ([mnaichuk](https://github.com/mnaichuk))
Now a user will get a single deposit address for ETH and ERC20 tokens. One deposit wallet will be able to have a few currencies.
Make sure to run related migration and configure Wallet <> Currency relations after.
* Add Wallet <> Currency association
* PaymentAddress now belongs to Member and a platform Wallet
* Admin endpoints to add and delete a currency to a wallet
- Encrypt Beneficiary data [\#2702](https://github.com/openware/peatio/pull/2702) ([mnaichuk](https://github.com/mnaichuk))
Encrypt Beneficiary `data` field using vault transit. The migration will automatically insert data for existing beneficiaries.
- Feature: Add user permissions [\#2730](https://github.com/openware/peatio/pull/2730) ([chumaknadya](https://github.com/chumaknadya))
Introduce permissions for users with `cancan` based on the YAML file. Config [example](https://github.com/openware/peatio/blob/master/config/abilities.yml)
- Feature: Introduce yaml based admin permissions in peatio [\#2643](https://github.com/openware/peatio/pull/2643) ([chumaknadya](https://github.com/chumaknadya))
Introduce permissions for admin endpoints with `cancan` based on the YAML file. Config [example](https://github.com/openware/peatio/blob/master/config/abilities.yml)
### New Features ###
- PostgreSQL support [\#2714](https://github.com/openware/peatio/pull/2714) ([calj](https://github.com/calj))
- Add the support of MariaDB ([calj](https://github.com/calj))
Databases documentation [postgress](https://github.com/openware/peatio/blob/master/docs/databases/postgresql.md) [mariadb](https://github.com/openware/peatio/blob/master/docs/databases/mariadb.md)
- Feature: Add Opendax wallet plugin [\#2735](https://github.com/openware/peatio/pull/2735) ([chumaknadya](https://github.com/chumaknadya))
* Feature: Add general wallet plugin
- Use JWT to authenticate peatio to the wallet
- Use SSL to secure the connection
* Minor changes for address creating
* Add ability to detect transaction from custom smart contract
Documentation for [Opendax Wallet](https://github.com/openware/peatio/blob/master/docs/peatio/opendax_wallet_plugin.md)
Co-authored-by: Maksym Naichuk <mnaichuk@heliostech.fr>
- Feature: Add ability to cancel orders on upstream [\#2745](https://github.com/openware/peatio/pull/2745) ([dpatsora](https://github.com/dpatsora))
We allow the cancelation of Finex orders through peatio Admin | User API. It will process cancel using AMQP.
- Add Gnosis base plugin [\#2744](https://github.com/openware/peatio/pull/2744) ([mnaichuk](https://github.com/mnaichuk))
Gnosis class inherits from ETH plugin except for the creation of address and transaction methods. With the Tower Gnosis plugin, you can process `multisig` withdrawals! More info about [gnosis](https://gnosis-safe.io/)
- Feature: Implement smart position changing for market and currencies [\#2682](https://github.com/openware/peatio/pull/2682) ([chumaknadya](https://github.com/chumaknadya))
We introduced smart position changing for markets and currencies (reorder all records in case of insert, etc.). More info [here](https://github.com/openware/peatio/blob/master/app/models/helpers/reorder_position.rb)
- Feature: limit number of currencies/markets [\#2660](https://github.com/openware/peatio/pull/2660) ([dinesh-skyach](https://github.com/dinesh-skyach))
Now you will be able to limit the number of currencies using ENV vars: MAX_CURRENCIES, MAX_MARKETS.
- Introduce CoinGecko API Endpoints [\#2698](https://github.com/openware/peatio/pull/2698) ([dpatsora](https://github.com/dpatsora))
- Introduce CMC API Endpoints [\#2696](https://github.com/openware/peatio/pull/2696) ([chumaknadya](https://github.com/chumaknadya))
### Enhancements ###
- Mask beneficiary account\_number on API level [\#2708](https://github.com/openware/peatio/pull/2708) ([chumaknadya](https://github.com/chumaknadya))
- Add transfer\_type in deposit and withdraw [\#2664](https://github.com/openware/peatio/pull/2664) ([mnaichuk](https://github.com/mnaichuk))
- Add rake task to fetch currency current price [\#2680](https://github.com/openware/peatio/pull/2680) ([chumaknadya](https://github.com/chumaknadya))
- Create member via Management API [\#2681](https://github.com/openware/peatio/pull/2681) ([dpatsora](https://github.com/dpatsora))
- Allow user to change the email [\#2750](https://github.com/openware/peatio/pull/2750) ([dpatsora](https://github.com/dpatsora))
- Define token type in currency model [\#2672](https://github.com/openware/peatio/pull/2672) ([chumaknadya](https://github.com/chumaknadya))
- Skip deposit fee collection transaction [\#2762](https://github.com/openware/peatio/pull/2762) ([mnaichuk](https://github.com/mnaichuk))
- Delete symbol from currency table [\#2676](https://github.com/openware/peatio/pull/2676) ([chumaknadya](https://github.com/chumaknadya))
- Enhancement: Return deposit address in account entity [\#2761](https://github.com/openware/peatio/pull/2761) ([mnaichuk](https://github.com/mnaichuk))
- Add the ability to exclude users by role from PnL calculation [\#2760](https://github.com/openware/peatio/pull/2760) ([calj](https://github.com/calj))
- Update drone config [\#2758](https://github.com/openware/peatio/pull/2758) ([calj](https://github.com/calj))
- Fix specs for PostgreSQL [\#2742](https://github.com/openware/peatio/pull/2742) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: Generate wallet settings on creation [\#2741](https://github.com/openware/peatio/pull/2741) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: Update withdraw limits logic [\#2740](https://github.com/openware/peatio/pull/2740) ([mnaichuk](https://github.com/mnaichuk))
- Add matching exchange for trading daemons. Delete deprecated amqp configs [\#2733](https://github.com/openware/peatio/pull/2733) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: Allow dot in currency code for API endpoints [\#2731](https://github.com/openware/peatio/pull/2731) ([chumaknadya](https://github.com/chumaknadya))
- Enhancement: Disable WLs if there are no in DB or zero limits [\#2724](https://github.com/openware/peatio/pull/2724) ([mnaichuk](https://github.com/mnaichuk))
- Enhancement: Add possibility to import and export Operation::Accounts [\#2720](https://github.com/openware/peatio/pull/2720) ([dpatsora](https://github.com/dpatsora))
- Update vault policies documentation [\#2712](https://github.com/openware/peatio/pull/2712) ([calj](https://github.com/calj))
- Add separate user and password for archive DB [\#2711](https://github.com/openware/peatio/pull/2711) ([dnfd](https://github.com/dnfd))
- Update dependencies [\#2710](https://github.com/openware/peatio/pull/2710) ([calj](https://github.com/calj))
- Optimize PnL main query [\#2699](https://github.com/openware/peatio/pull/2699) ([calj](https://github.com/calj))
- Enhancement: Add export:configs Rake task [\#2693](https://github.com/openware/peatio/pull/2693) ([vshatravenko](https://github.com/vshatravenko))
- Enhancement: Add import:configs Rake task [\#2692](https://github.com/openware/peatio/pull/2692) ([vshatravenko](https://github.com/vshatravenko))
- Enhancement: trigger custom image build [\#2691](https://github.com/openware/peatio/pull/2691) ([josadcha](https://github.com/josadcha))
- Enhancement: add admin currencies fetch filters [\#2678](https://github.com/openware/peatio/pull/2678) ([oyershov](https://github.com/oyershov))
- Enhancement: Delete symbol from currency table [\#2676](https://github.com/openware/peatio/pull/2676) ([chumaknadya](https://github.com/chumaknadya))
- Add rake task for load trades and build k-lines. Update 2-4 migration documentation [\#2675](https://github.com/openware/peatio/pull/2675) ([mnaichuk](https://github.com/mnaichuk))
- Update CI to build images for branches matching {fix,integration}/\* [\#2674](https://github.com/openware/peatio/pull/2674) ([calj](https://github.com/calj))
- Enhancement: Add ability to create market by engine name [\#2671](https://github.com/openware/peatio/pull/2671) ([chumaknadya](https://github.com/chumaknadya))
- Update peatio-bitgo version. Change rid length for withdraw [\#2669](https://github.com/openware/peatio/pull/2669) ([mnaichuk](https://github.com/mnaichuk))
- Improve Engines and Markets seed [\#2665](https://github.com/openware/peatio/pull/2665) ([mnaichuk](https://github.com/mnaichuk))
- Speedup tests execution [\#2661](https://github.com/openware/peatio/pull/2661) ([calj](https://github.com/calj))- Fix: Add from\_addresses on deposit creation [\#2656](https://github.com/openware/peatio/pull/2656) ([mnaichuk](https://github.com/mnaichuk))
- Renew of vault token with ENV. Remove sensitive data from admin entities [\#2568](https://github.com/openware/peatio/pull/2568) ([mnaichuk](https://github.com/mnaichuk))
- Improve vault support [\#2544](https://github.com/openware/peatio/pull/2544) ([mnaichuk](https://github.com/mnaichuk))
### Bug Fixes ###
- Remove market creation validation for unvisible market [\#2765](https://github.com/openware/peatio/pull/2765) ([mnaichuk](https://github.com/mnaichuk))
- Update currency price field [\#2756](https://github.com/openware/peatio/pull/2756) ([mnaichuk](https://github.com/mnaichuk))
- Fix: tx\[input\] fetch [\#2746](https://github.com/openware/peatio/pull/2746) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Add ability to configure wallet features from settings [\#2738](https://github.com/openware/peatio/pull/2738) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Abilities for user permissions [\#2736](https://github.com/openware/peatio/pull/2736) ([chumaknadya](https://github.com/chumaknadya))
- Fix: Dont mask beneficiary account number on admin endpoints [\#2729](https://github.com/openware/peatio/pull/2729) ([chumaknadya](https://github.com/chumaknadya))
- Update WalletService trigger\_webhook\_event method [\#2727](https://github.com/openware/peatio/pull/2727) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Add ability to update wallet settings [\#2725](https://github.com/openware/peatio/pull/2725) ([chumaknadya](https://github.com/chumaknadya))
- Fix: Remove partial wallet settings update [\#2722](https://github.com/openware/peatio/pull/2722) ([mnaichuk](https://github.com/mnaichuk))
- Fix InfluxDB sharding spec [\#2716](https://github.com/openware/peatio/pull/2716) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Add error message for adjustment creation if user balance is insufficient [\#2715](https://github.com/openware/peatio/pull/2715) ([Kohelbekker](https://github.com/Kohelbekker))
- Fix: do not fail on start if VAULT\_TOKEN is unset [\#2709](https://github.com/openware/peatio/pull/2709) ([calj](https://github.com/calj))
- Update vault rails gem. Fix update wallet params [\#2707](https://github.com/openware/peatio/pull/2707) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Update import/export rake tasks for payment\_addresses [\#2703](https://github.com/openware/peatio/pull/2703) ([mnaichuk](https://github.com/mnaichuk))
- Remove uri validation from wallet model [\#2700](https://github.com/openware/peatio/pull/2700) ([mnaichuk](https://github.com/mnaichuk))
- Fix database migration for MariaDB [\#2694](https://github.com/openware/peatio/pull/2694) ([calj](https://github.com/calj))
- Fix: Wallet links update. Deposit spread wallet recalculation [\#2687](https://github.com/openware/peatio/pull/2687) ([mnaichuk](https://github.com/mnaichuk))
- Fix: Add wallet link && fix blockchain\_key on currency creation [\#2686](https://github.com/openware/peatio/pull/2686) ([chumaknadya](https://github.com/chumaknadya))
- Fix: Update spread deposit with currency price [\#2685](https://github.com/openware/peatio/pull/2685) ([mnaichuk](https://github.com/mnaichuk))
- Fix wallet load\_balance method. Update WalletBalances job [\#2667](https://github.com/openware/peatio/pull/2667) ([mnaichuk](https://github.com/mnaichuk))

View File

@@ -0,0 +1,3 @@
# Peatio releases
**Peatio respects a modified version of [SemVer](http://semver.org), similar to the Ruby on Rails project.**

25
docs/roadmap.md Normal file
View File

@@ -0,0 +1,25 @@
# Peatio Roadmap
## v2.4
* Incremental Orderbook via WS
* Moving historical data of kline and trades into influxDB
* Performance improvements for matching latency
* Migration to Rack JWT
* Native Support for Bitgo
* Rack tasks for exporting and importing config and users
## v2.5
* Integration of ranger back into peatio
* Ability to manage tickers with incremental push from Ranger
* AMQP Queue normalization unify using EventAPI
* API rate limiter per user
* CSV export and database archiving
* Support for Remote orderbook
* Remove SlaveBook and rework global state
* Optimize memory usage of Peatio deployments
## v3.0
* Support for blockchain multicurrency deposits

31
docs/roles.md Normal file
View File

@@ -0,0 +1,31 @@
| Blockchain | Superadmin | Admin | Accountant |Compliance | Technical| Support | Member| Broker| Trader|
| ---------------------- |:------------:|:------:|:-----------:|:---------:|:--------:|:-------:|:-----:|:-----:|------:|
| Create blockchain | RW | RW | NO | NO | RW | NO | NO |NO |NO |
| Change blockchain field | RW | RW | NO | NO | RW | NO | NO |NO |NO |
| **Currencies** | | | | | | | |
|Create currency | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|Change currency field | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|**Markets** | | | | | | | |
|Create market | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|Change market field | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|**Wallets** | | | | | | | |
|Create wallet | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|Change wallet field | RW | RW | NO | NO | RW | NO | NO |NO |NO |
|**Deposits** | | | | | | | |
|Read user's deposits | RO | RO | RO | RO | RO | RO | NO |NO |NO |
|Collect deposits | RW | RW | NO | NO | NO | NO | NO |NO |NO |
|Create fiat deposit | RW | RW | RO | NO | NO | NO | NO |NO |NO |
|Accept fiat deposit | RW | RW | NO | NO | NO | NO | NO |NO |NO |
|Reject fiat deposit | RW | RW | NO | NO | NO | NO | NO |NO |NO |
|**Withdraws** | | | | | | | |
|Read withdrawals | RW | RW | RO | RO | RO | RO | NO |NO |NO |
|Accept withdrawals | RW | RW | NO | NO | NO | NO | NO |NO |NO |
|Reject withdrawals | RW | RW | NO | NO | NO | NO | NO |NO |NO |
|**Members** | | | | | | | |
|Read user's balances | RW | RO | RO | RO | RO | RO | NO |NO |NO |
|Read user's deposit address | RW | RO | RO | RO | RO | RO | NO |NO |NO |
|**Operations** | | | | | | | |
|Read platform's operations | RW | RW | RO | RO | RO | RO | NO |NO |NO |
|**Accounting** | | | | | | | |
|Read exchange balance sheet | RW | RW | RO | RO | NO | RO | NO |NO |NO |
|Read exchange income statement| RW | RW | RO | RO | NO | RO | NO |NO |NO |

View File

@@ -0,0 +1,36 @@
# Whitelisted smart contracts
This doc describes how you can use whitelisted smart contract feature to detect deposits from third party smart contracts.
| Term | Definition |
| ------------------ | ------------------------------------------------------------ |
| Description | The smart contract info. |
| Address | Address of whitelisted smart contract. |
| State | State of whitelisted smart contract |
| Blockchain key | Identify in which blockchain system will detect deposit from whitelisted smart contract |
There are many third-party smart contracts with which you can send eth or erc-20.
Example of transaction: https://etherscan.io/tx/0xeb92797eb91f53ce7bb68abaf3fd3198980d971dd42f9fcb6eb1272ef3ef2a0e
In this transaction TOM erc-20 (`0xf7970499814654cd13cb7b6e7634a12a7a8a9abc`) was transferred
from `0x095273adb73e55a8710e448c49eaee16fe115527`
to `0xbbd602bb278edff65cbc967b9b62095ad5be23a3`
using `0x6c0b51971650d28821ce30b15b02b9826a20b129` smart contract.
Before Peatio was not able to detect this deposit because the system checks `to` entry in eth raw transaction and
compare it with existing currency smart contracts in DB.
With the Whitelisted smart contracts feature the system will able to detect deposits from third-party smart contracts.
You just need to add it through Tower (Settings tab -> Whitelisted smart contracts) and link it to the right blockchain (via blockchain_key). Also, there is the ability to load CSV files with several smart contracts.
![image](images/peatio/tower_whitelisted_contracts.png)
Through rails console:
```ruby
WhitelistedSmartContract.create(description: "New third party contracts", address: "0x6c0b51971650d28821ce30b15b02b9826a20b129", state: "active", blockchain_key: "eth-mainet")
```

View File

@@ -0,0 +1,17 @@
## How to process distribution for users
1. Create `csv` files with the following format
### Distribution table
| uid | currency_id | amount |
|---------------|-------------|--------|
| ID1000003837 | usdt | 100 |
uid, currency_id, amount - required params
2. For process distribution
```ruby
bundle exec rake distribution:process['file_name.csv']
```

31
docs/tasks/import.md Normal file
View File

@@ -0,0 +1,31 @@
## How to import users and account balances database Peatio
1. Create `csv` files for users and accounts with those templates.
### Users table
| uid | email | level | role | state | referral_uid |
|---------------|----------------|-------|--------------|---------|---------------|
| ID1000003837 | peatio@tech.io | 3 | superadmin | active | ID1000003828 |
uid, email - require params
### Accounts table
| uid | currency_id | main_balance | locked_balance |
|---------------|--------------|--------------|------------------|
| ID1000003837 | ETH | 10 | 5 |
uid, currency_id - require params
2. For import users
```ruby
bundle exec rake import:users['file_name.csv']
```
3. For import accounts
```ruby
bundle exec rake import:accounts['file_name.csv']
```

View File

@@ -0,0 +1,29 @@
## Archive and delete cancelled orders without any trade older than one week
This job archives orders that were cancelled more than a week ago and didn't produce any trade.
Those orders are stored in the archive database and cleaned up from the main database.
### Prerequisites
* Deploy archive database
* Configure database.yml (archive_db section)
For process order archive job:
```bash
bundle exec rake job job:order:archive
```
New DB Job record:
| Column | Value |
|--------|-------|
| id | 10 |
| name | archive_orders |
| pointer | 1607603942 |
| counter | 6674 |
| data | nil |
| error_code | 0 |
| error_message | nil |
| started_at | Thu 10 Dec 2020 13:39:02 CET +01:00 |
| finished_at | Thu 10 Dec 2020 13:39:28 CET +01:00 |

27
docs/tasks/order_close.md Normal file
View File

@@ -0,0 +1,27 @@
## Cancel orders older than max_age
1. Set ORDER_MAX_AGE env in seconds (e.g. 28 days):
```bash
export ORDER_MAX_AGE=2_419_200
```
2. For process order cancel job:
```bash
bundle exec rake job job:order:close
```
New DB Job record:
| Column | Value |
|--------|-------|
| id | 9 |
| name | close_orders |
| pointer | 1607603942 |
| counter | 2000 |
| data | nil |
| error_code | 0 |
| error_message | nil |
| started_at | Thu 10 Dec 2020 13:39:02 CET +01:00 |
| finished_at | Thu 10 Dec 2020 13:39:28 CET +01:00 |

View File

@@ -0,0 +1,38 @@
## Compact order liabilities using Stored Procedure
Submit and cancel order processes create 4 records in the liabilities table (classic bots behaviour).
Because of those processes liabilities table can grow to significant sizes.
Compaction job will process liabilities for the previous week (by default) group them by code, currency_id, and date:
```sql
GROUP BY code, currency_id, member_id, DATE(`created_at`)
```
Due to the size of the liabilities table, it is recommended to run this job every day.
For process order liabilities compaction job:
```bash
bundle exec rake job job:liabilities:compact_orders
```
It will compact liabilities for orders from previous week. Also you can specify timerange (e.g.):
```bash
bundle exec rake job job:liabilities:compact_orders['2020-12-09 00:00:00','2020-12-10 00:00:00']
```
New DB Job record:
| Column | Value |
|--------|-------|
| id | 8 |
| name | compact_orders |
| pointer | 1607603942 |
| counter | 6675 |
| data | nil |
| error_code | 0 |
| error_message | nil |
| started_at | Thu 10 Dec 2020 13:39:02 CET +01:00 |
| finished_at | Thu 10 Dec 2020 13:39:28 CET +01:00 |

155
docs/vault.md Normal file
View File

@@ -0,0 +1,155 @@
# Vault configuration
## Introduction
This document describe how to create vault tokens in order to configure **peatio-rails** to be able **to encrypt** secrets, **to renew** token and **to manage** totp, to configure **peatio-crypto-daemons** to be able **to encrypt** secrets, **to decrypt** secrets, **to renew** token, to configure **peatio-upstream-proxy** to be able **to decrypt** secrets, **to renew** token.
## Connect to vault
You can validate it works running the following command:
```bash
$ vault status
Type: shamir
Sealed: false
Key Shares: 1
Key Threshold: 1
Unseal Progress: 0
Unseal Nonce:
Version: 1.3.4
Cluster Name: vault-cluster-650930cf
Cluster ID: 9f40327d-ec71-9655-b728-7588ce47d0b4
High-Availability Enabled: false
```
## Create ACL groups
### Create the following policy files
**peatio-rails.hcl**
```bash
# Manage the transit secrets engine
path "transit/keys/*" {
capabilities = [ "create", "read", "list" ]
}
# Encrypt engines secrets
path "transit/encrypt/opendax_engines_*" {
capabilities = [ "create", "read", "update" ]
}
# Encrypt wallets secrets
path "transit/encrypt/opendax_wallets_*" {
capabilities = [ "create", "read", "update" ]
}
# Encrypt beneficiaries data
path "transit/encrypt/opendax_beneficiaries_*" {
capabilities = [ "create", "read", "update" ]
}
# Decrypt beneficiaries data
path "transit/decrypt/opendax_beneficiaries_*" {
capabilities = [ "create", "read", "update" ]
}
# Renew tokens
path "auth/token/renew" {
capabilities = [ "update" ]
}
# Lookup tokens
path "auth/token/lookup" {
capabilities = [ "update" ]
}
# Verify an otp code
path "totp/code/opendax_*" {
capabilities = ["update"]
}
```
**peatio-crypto-daemons.hcl**
```bash
# Manage the transit secrets engine
path "transit/keys/*" {
capabilities = [ "create", "read", "list" ]
}
# Encrypt Payment Addresses secrets
path "transit/encrypt/opendax_payment_addresses_*" {
capabilities = [ "create", "read", "update" ]
}
# Decrypt Payment Addresses secrets
path "transit/decrypt/opendax_payment_addresses_*" {
capabilities = [ "create", "read", "update" ]
}
# Decrypt wallets secrets
path "transit/decrypt/opendax_wallets_*" {
capabilities = [ "create", "read", "update" ]
}
# Renew tokens
path "auth/token/renew" {
capabilities = [ "update" ]
}
# Lookup tokens
path "auth/token/lookup" {
capabilities = [ "update" ]
}
```
**peatio-upstream-proxy.hcl**
```bash
# Manage the transit secrets engine
path "transit/keys/*" {
capabilities = [ "create", "read", "list" ]
}
# Decrypt Engines secrets
path "transit/decrypt/opendax_engines_*" {
capabilities = [ "create", "read", "update" ]
}
# Renew tokens
path "auth/token/renew" {
capabilities = [ "update" ]
}
# Lookup tokens
path "auth/token/lookup" {
capabilities = [ "update" ]
}
```
### Create the ACL groups in vault
```bash
vault policy write peatio-rails peatio-rails.hcl
vault policy write peatio-crypto-daemons peatio-crypto-daemons.hcl
vault policy write peatio-upstream-proxy peatio-upstream-proxy.hcl
```
### Create applications tokens
```bash
vault token create -policy=peatio-rails -period=240h
vault token create -policy=peatio-crypto-daemons -period=240h
vault token create -policy=peatio-upstream-proxy -period=240h
```
## Configure Peatio
Set those variables according to your deployment:
```bash
export VAULT_ADDR=http://127.0.0.1:8200
export VAULT_TOKEN=s.jyH1vmrOmkZ0FZZ0NZtgRenS
export VAULT_APP_NAME=opendax
```

65
docs/workers.md Normal file
View File

@@ -0,0 +1,65 @@
# Peatio daemons
## amqp:deposit_collection
This daemon transfer incoming deposits from deposit wallet to withdraw wallets (hot, warm, cold).
## amqp:deposit_collection_fees
This daemon transfer fees for deposit collection paying and send deposit_collection request to amqp:deposit_collection.
## amqp:deposit_coin_address
This daemon creates new addresses for you.
## amqp:influx_writer
This daemon reads from peatio.trade exchange and records trades to InfluxDB.
## amqp:market_ticker
This daemon updates market ticker when some orders or trades are created / updated.
## amqp:matching
This daemon matches orders and sends them to amqp:trade_executor.
## amqp:order_processor
This daemon processes cancelation of orders.
## amqp:pusher_market
This daemon delivers new trade to Ranger.
## amqp:pusher_member
This daemon delivers events to private member Ranger channel.
## amqp:slave_book
This daemon keeps copy of in-memory orderbook from amqp:matching and updates various data stored in Redis which is needed for trading UI.
## amqp:withdraw_coin
This daemon performs withdraw.
## amqp:trade_executor
This daemon performs partial or full fullfilment of two orders.
## daemon:blockchain
This daemon monitors blockchain for incoming deposits and withdrawal and updates their state on the database.
## daemon:global_state
This daemon send orderbook to Ranger every 5 seconds.
## daemon:k
This daemon updates k-lines every 15 seconds.
## daemon:withdraw_audit
This daemon validates withdrawals and sends them to amqp:withdraw_coin.

Binary file not shown.

View File

@@ -0,0 +1,24 @@
```mermaid
graph LR
A[client] -->|request| B(proxy)
B --> |private_ip|C(BaseApp)
B --> D(Gateway)
D --> |private_ip|E(peatio)
D --> |private_ip|F(barong)
D --> |private_ip|G(ranger)
F --> |database|H(mysql)
E --> |database|H
F --> |queue|I(rabbitmQ)
E --> K(processor)
E --> L(matching)
E --> M(executor)
K --> |queue|I
L --> |queue|I
M --> |queue|I
G --> |queue|I
E --> |timebase database|J(influxDB)
E --> |encrypt and decrypt|vault
F --> |encrypt and decrypt|vault
```

View File

@@ -0,0 +1,47 @@
# Blockchain : Bitcoin
## how setup node
First, install bitcoind (Daemon for connecting main Bitcoin Blockchain), follow below guide sites:
- [1 setup](https://gist.github.com/rjmacarthy/b56497a81a6497bfabb1)
- [2 setup](https://stopanddecrypt.medium.com/a-complete-beginners-guide-to-installing-a-bitcoin-full-node-on-linux-2021-edition-46bf20fbe8ff)
- [3 setup](https://www.devmanuals.net/install/ubuntu/ubuntu-12-04-lts-precise-pangolin/install-bitcoind.html)
so run daemon and must be uptodate and contains all of blocks<br/>
** Start bitcoind as daemon** <br/>
*bitcoind --daemon*
### then create wallet or if created before, must load them:<br/>
#### for loading wallet
first ssh on btc server , then:<br>
*bitcoin-cli loadwallet btc-hot*<br/>
*bitcoin-cli -testnet loadwallet btc-dep*
#### for create walelt
*bitcoin-cli -testnet createwallet btc-fee*<br/>
*bitcoin-cli createwallet btc-dep*<br/>
###### `btc-dep` or `btc-hot` is optional name
### So, create new address by each wallet and keep them for next step (create wallet in panel)
- bitcoin-cli -testnet -rpcwallet=btc-fee getnewaddress
- bitcoin-cli -rpcwallet=btc-dep getnewaddress
- bitcoin-cli -testnet -rpcwallet=btc-fee getnewaddress
### Now create relative blockchain, currency and wallet record in the panel
[follow this guide site](https://medium.com/openware/how-to-configure-blockchain-node-in-the-tower-opendax-5e75e3264e18) <br/>
example for blockchain server field:
- http://rpcuser:rpcpass@46.209.13.2:18332
- http://rpcuser:rpcpass@192.168.15.100:8332
example for wallet uri field:
- http://rpcuser:rpcpass@185.194.78.52:#{port}/wallet/#{wallet_name}
- http://user1:changeme@46.209.13.2:18332/wallet/btc-dep
`18332`, `8332` these are ports that daemon listen on it, and the Peatio talks to it with `jsonrpc`.<br/>
**ports**, **user** and **password** can be set in this file : `bitcoin.conf`
- regtest ports are 18443, 18444
- testnet ports are 18332, 18333
- mainnet ports are 8332, 8333

View File

@@ -0,0 +1,87 @@
# ether: set up node
###### Sprint: ?
###DOC
we setup our node with geth.Geth(Go Ethereum) is a command line interface for running Ethereum node implemented in Go Language. Using Geth you can join Ethereum network, transfer ether between accounts or even mine ethers.
###steup
You can start Geth in one of three different sync modes using the --syncmode "<mode>" argument that determines what sort of node it is in the network.
These are:
1. Full: Downloads all blocks (including headers, transactions, and receipts) and generates the state of the blockchain incrementally by executing every block.
2. Fast: Downloads all blocks (including headers, transactions and receipts), verifies all headers, and downloads the state and verifies it against the headers.
3. Snap (Default): Same functionality as fast, but with a faster algorithm.
4. Light: Downloads all block headers, block data, and verifies some randomly.
we used light mode to better speed in syncing and decrease needed storage.
Ethereum has many networks:
1. mainnet
2. testnet
1. Görli(goerli)<br >
A proof-of-authority testnet that works across clients.
2. Kovan:<br >
A proof-of-authority testnet for those running OpenEthereum clients.
3. Rinkeby:<br >
A proof-of-authority testnet for those running Geth client.
4. Ropsten:<br >
A proof-of-work testnet. This means it's the best like-for-like representation of Ethereum.
we wrote an script to setup eth node:
```shell
geth --goerli --http --http.vhosts="" --http.addr=0.0.0.0 --datadir /home/ubuntu/.ethereum --rpcaddr=0.0.0.0 --rpcport=8545 --port=30303 --rpcapi="admin,db,debug,personal,eth,net,web3" --rpccorsdomain="" --rpcvhosts="*" --syncmode="light" --cache=2048 --allow-insecure-unlock --nousb
```
* in goerli testnet and light mode
you can see more detail in [geth docs](https://geth.ethereum.org/docs/interface/command-line-options) or use
```shell
geth --help
```
after installation
###some commands and tips
1. install the geth on your machine<br/>
commands for ubuntu
- sudo add-apt-repository -y ppa:ethereum/ethereum
- sudo apt-get update
- sudo apt-get install ethereum
2. connect to console of Eth server:
geth attach `http://ip:prot`
3. personal.newAccount()<br >
Generates a new private key and stores it in the key store directory. The key file is encrypted with the given passphrase. Returns the address of the new account.<br >
At the geth console, newAccount will prompt for a passphrase when it is not supplied as the argument.
```shell
> personal.newAccount()
Passphrase:
Repeat passphrase:
"0x5e97870f263700f46aa00d967821199b9bc5a120"
```
2. for checking that geth is updated or not you can use:
```shell
> eth
```
for all informations
```shell
> eth.blockNumber
```
for getting only last received block<br >
and compare it with [etherscan](https://etherscan.io/)
3. to connect to your node with js console you can use:
```shell
geth attach {$your_node_anddress}
```

View File

@@ -0,0 +1,51 @@
# Blockchain Deposit
[please read first](daemon.md)
### file:
- {$Dena_path}/app/workers/daemons/blockchain.rb
### implementation
daemon dockerize by below code and file:
- bash -c "bundle exec ruby lib/daemons/daemons.rb blockchain" (called in Alvand Service up rake)
- {$Dena_path}/lib/daemons/daemons.rb
Blockchain daemon as one **thread** for each active blockchain, process blocks and filter platform deposits.<br />
this daemon use BlockchainService class in per one thread.<br/>
that class recognizes its `adapter` (coin-connectors or coin-middleman) with help of the parameter that is passed to it when initialized,
this parameter is **the blockchain DB record.**<br/>
also, this class has standard functions that any coin-connectors must obey, so this class has two hands, with one hand connect to local DB and with another hand talk to the relevant Blockchain with help of `the adapter`.<br/>
each coin has itself adapter that can be the Gem.<br />
responsibility of these Adapters that connect to the related blockchain and doing my needed methods.<br/>
this daemon is kept alive by an infinite loop that in every 30 seconds check the active blockchains.<br />
also, in this 30-second time, check updated time of the blockchain or currencies record, if they have been newly updated time,
the blockchain thread will be reset.<br />
when the blockchain thread is reset, the last_seen_block will become **nil**.</br>
BlockchainService class fetches relative blocks with help the Adapter,<br />
and find transactions that included our users addresses (users addresses were saved in local DB).<br />
after each loop of the Blockchain investigation, we update the Variable that has kept the last seen block number.<br />
and also update the Height column of the blockchain record.<br />
We are waiting for the N number of confirmations.<br />
if height column of the blockchain record plus(+) the min confirmation, was bigger than the Adapters last seen block variable, synchronization will be skipped, and try again after 10 seconds<br />
from the blockchain height to Adapters last_seen_block, the `process_block` function of **BlockchainService** class will be executed for each block.<br/>
at last the height column will be updated.
#### process_block function
1. fetch block by Adapter
2. find relative deposits (destination address of blocks in our user address).
3. find relative withdraws (hash transaction of blocks in our user confirming withdraws `txid`).
4. Per deposit Blockchain, we update or create Db record and changing users balances.
5. Per withdraw in Blockchain, we find Db records by `confirming` state, then update record state by the blockchain transaction,
that was fetched before again by its the Adapter. so, at last, we will unlock and update user balances
```mermaid
graph LR
A(Peatio) -->|Blockchain stuffs| B[BlockchainService using adapter]
B --> |Blockchain stuffs| D((Btc Blockchain))
B --> |Blockchain stuffs| E((Eth Blockchain))
B --> |Blockchain stuffs| F((...))
B --> A
D --> B
E --> B
F --> B
```

View File

@@ -0,0 +1,29 @@
# Blockchain Collection fee
[please read first](daemon.md)
### files:
- {$Dena_path}/app/workers/daemons/deposit.rb
- {$Dena_path}/app/services/wallet_service.rb
### implementation
during blockchain deposit daemon, WalletService asks its Adapter (by passing The relevant deposit wallet) that the `prepare_deposit_collection!` method was implemented or not.<br />
if not, the daemon kept continues its process, but if that method existed in the coin Adapter, the deposit daemon call the `collect_fee` method on the deposit DB record.<br />
#### collect_fee function
1. Check the spread column of the deposit to find was filled or not. if not call `spread_between_wallets!` from the Deposit model.
2. Active relevant fee wallet will be found from DB. if not found, we will back to the deposit daemon process.
3. Create WalletService object by passing active fee wallet and run `deposit_collection_fees!` method on the deposit record.
4. `deposit_collection_fees` method, run `prepare_deposit_collection`
5. `prepare_deposit_collection` method will have a unique implementation for each coin (blockchain),but eventually, the output must be a transaction that in addition to sending into the relevant blockchain, also will be saved in the local DB.
6. Change the state column of the deposit record from `processing` to `fee_processing`
```mermaid
graph TD
A((Depoist Daemon)) -->|deposit record| B[WalletService ]
B --> |the Depoist Wallet Record| C{Adapter}
C --> |`prepare_deposit_collection` is not impelemented |A
C --> |`prepare_deposit_collection` is impelemented| E(WalletService)
E --> |the Fee Wallet Record| C
C --> D(`deposit_collection_fees!`)
D --> |change state to fee_processing|A
```

View File

@@ -0,0 +1,65 @@
# Blockchain Deposit Watcher
Peatio daemons are controlled by this gem: [God](http://godrb.com/).
##### note: just we use the God if want using The Peatio in local without docker, in collection service, daemons handle by docker container.
## Daemon
##### start daemon with the god:
`god -c lib/daemons/daemons.god` <br/>
**When the Peatio is being initialized, the God starts all daemons**<br />
##### stop daemon with the god:
`god stop`. *God will still be up.*<br />
##### stop God and all daemons:
`god terminate`
##### restart God: <br />
`god restart`
##### status God: <br />
`god status`
#### [please read it](../../../README.md)
## Deposit Daemon
###### this Daemon, become a docker service by daemons.yaml that call in service.rake
[first read deposits_flow](../../../docs/peatio/deposits_flow.md)
**so we use new version of deposit**
#### files:
- {$Dena_path}/app/workers/daemons/deposit.rb
- {$Dena_path}/app/workers/daemons/blockchain.rb
#### implementation
daemon dockerize by below code and file:
- bash -c "bundle exec ruby lib/daemons/daemons.rb deposit" (called in Alvand Service up rake)
- {$Dena_path}/lib/daemons/daemons.rb
We decided to remove to AMQP base deposit daemons and create a new deposit daemon that will work on deposit states changes
and will prevent immediate proceeding of erc20 deposits.
New deposit process diagram:
![image](../../images/peatio/new_deposits_flow.png)
1. Blockchain daemon process blocks and filter platform deposits and save them in our DB. [document](blockchain.md) <br />
3. In the deposit daemons we select each 60s deposits with state `processing` and `fee_processing`.
4. For `processing` deposits we are checking if plugin implement method `prepare_deposit_collection!` if it doesn't we immediately process the deposit and collect deposit to the `hot`, `warm`, `cold` wallets.<br />
this collection is done with help of WalletService class, that one of its responsibility is **spreading** between wallets.
[read more about WalletService](../withdraw/withdraw-coin.md)<br/>
every deposit record has column named `spread` that getting array value like this:<br />
`[{"to_address"=>"xyxzx", "amount"=>"0.00083", "currency_id"=>"btc", "status"=>"pending", "hash"=>"dcffd5b7fabaa"}]`,<br />
valued by (`spread_between_wallets!` *function* in deposit model) that was called in this daemon<br/>
each row of the Spread array, will become transaction record and will be send to the Blockchain by WalletService and its the Adapter (`collect_deposit!` function).<br />
If plugin implement method `prepare_deposit_collection!` daemon processing of collection fees and change deposit state to `fee_processing`.<br />
For deposits with `fee_processing` state, we select each minute deposits that have `updated_at` older than 5 minutes and process them. With time condition we are sure that fee transaction has already been executed.<br />
```mermaid
graph TD
A((Blockchain)) -->|Deposit| B[Blockchain Daemon]
B --> |waiting for numbers of confirmations| C[Deposit Daemon]
D(BlockchainService) --> B
E(WalletService) --> C
```

View File

@@ -0,0 +1,57 @@
# Deposit: Fiat
###### Sprint: 5
### Outcome:
Users can do fiat deposits with the Help of the Vandar service.
### Implementation description:
#### Endpoints:
POST {$domain}/api/v2/peatio/account/deposits/fiat <br/>
POST {$domain}/api/v2/peatio/account/deposits/confirm<br/>
#### File destination:
{$Dena_Path}/app/api/v2/account/deposits.rb
#### Commits:
3b189b07<br/>
d436176b<br/>
1cc9fb29<br/>
9a6d7864<br/>
5994b163<br/>
7769e86a<br/>
7dea7777<br/>
#### What did we implement:
we implemented a new client route for user, to they can deposit their money and charge their accounts
### TODO
now we dont show any information of the deposit result to user, so in the result of the Vandar the amount perhaps remains as Rial
```mermaid
sequenceDiagram
Title: Depost Fiat
note over User,Ranj:The description and factorNumber are optionals
note over User,Ranj:callback_url parameter use for Vandar Service\n to redirect Bank Gateway into my system after deposit
User->>Ranj:amount, callback_url, currency, card, **factorNumber**, **description**
Ranj->>Dalan:POST: after client side checking
Dalan->>Ranj:4xx if lose any required parameters
note over Dalan,Vandar:The Vandar service has own documentation
Dalan->>Ranj:4xx if entered Card number not exist in current user valid Card number list
Dalan->>Ranj:new deoposit recored created
Dalan->>Ranj:4xx if any model validation become false
Dalan->>Vandar:POST valid_card_number, amount, callback_url, description
Vandar->>Dalan:A new deposit token will be generated for Bank Gateway
Dalan->>Ranj: pass generated Token
Ranj->>User:if token present redirect user's page to Bank Gateway \n otherwise, show errors in the Vandar response and process finished
User-->>Vandar: entering bank information for doing deposit
Vandar->>Ranj:GET pass generated token to callback_url
Ranj->>Dalan: POST generated token for confirming step
Dalan->>Ranj:at first, we check the database to check the status of the deposit that was unique by the generated token.\n show record result if txid present in DB,\n otherwise ask The Vandar for result of this deposit.
Dalan->>Vandar: POST generated token to find transaction
Vandar->>Dalan: pass result of transaction
Dalan->>Vandar: POST generated token to verify transaction
Dalan->>Ranj: update deposit record in DB (txid) and charge user balane
Ranj->>User: notify the user that the deposit is done.
```

View File

@@ -0,0 +1,49 @@
# Spread between wallets method
[Please read first](daemon.md)
### files:
- {$Dena_path}/app/workers/daemons/deposit.rb
- {$Dena_path}/app/models/deposit.rb
### implementation
If you have read the deposit doc, you know this function where is called.
#### spread_between_wallets! function
1. Will Return to ex-process if the Spread column had value.
2. Finding the Deposit wallet form currency and pass it as input param to the WalletService class to create the object.
3. Calling `spread_deposit` function from **WalletService** class for the deposit record
4. Update the spread column for DB record with return value from step **3**.
#### spread_deposit function
1. The Adapter will be configured with the wallet record data and the relevant blockchain and currency setting
2. Array list by data of the withdraw wallet form DB (HOT WARM COLD)
3. Map them to new data by name **destination_wallets**:
- `address` : the wallet address
- `balance` : the current coin balance of wallet
- `max_balance` : how many coins the wallet can host
- `min_collection_amount` : the minimum of accepted deposit (set in the Admin panel)
- `skip_deposit_collection` : boolean type to skip deposit or not (set in the Admin panel)
4. Set the zero the balance for the last wallet. Since last wallet is considered to be the most secure we need always. All money which doesn't fit to other wallets will be collected to last wallet.
5. Call `spread_between_wallets` from *WalletService* with the deposit record and the **destination_wallets**
#### spread_between_wallets function
1. Returning empty array if deposit amount smaller than the minimum of `min_collection amount` of wallets.
2. left_amount variable is initialized with amount of the deposit (*original_amount*)
3. starting a loop on `destination_wallets`.
4. `amount_for_wallet` = choose the minimum value between available wallet balance and left_amount
5. Setting zero for `amount_for_wallet` if this variable smaller than `min_collection_amount`
6. `left_amount` will equal to (`left_amount` minus `amount_for_wallet`)
7. If amount left is too small we will not able to collect it.So we collect everything to current wallet.<br/ >
`amount_for_wallet` = `amount_for_wallet` + `left_amount` and `left_amount` = 0
8. Creating `Peatio::Transaction` object:
- to_address : `to_address` from **destination_wallets**
- amount : `amount_for_wallet`
- currency_id: currency_id of the deposit record
- status : :skipped if `skip_deposit_collection` is true
9. Ending the loop on `destination_wallets` and now we have `spread` variable that includes **transactions**.
10. If deposit amount doesn't fit to any wallet, collect it to the last one. (`left_amount` doesnt become zero).
11. Remove zero and skipped transactions from spread.
12. Return `spread` variable.

View File

@@ -0,0 +1,125 @@
# Market: new order type imp
###### Sprint: ?
### Outcome:
we need to store new order types in ram.(OCO, stop-order- stop-limit-order)
always we should follow openware road map so we implement order types just like what they did.
so we create ne models and class with nested initializing.
#### File destination:
{$Dena_Path}/app/trading/matching/engine.rb
{$Dena_Path}/app/trading/matching/oco_order.rb
{$Dena_Path}/app/trading/matching/special_order_book.rb
{$Dena_Path}/app/trading/matching/special_order_book_manager.rb
{$Dena_Path}/app/trading/matching/stop_order.rb
{$Dena_Path}/app/trading/matching/stop_limit_order.rb
#### Commits:
5661b7a9c1
f71c7724b1
79e4aec6bf
d5e67664b2
8c0d87cca8
25fd01c802
f40cb20c7d
<br >
<br >
<br >
<br >
#### What did we implement:
lets see how does every order work:
1.stop order:
A stop order, also referred to as a stop-loss order, is an order to buy or sell a stock once the price of the stock reaches a specified price, known as the stop price. When the stop price is reached, a stop order becomes a market order. A buy stop order is entered at a stop price above the current market price. Investors generally use a buy stop order to limit a loss or to protect a profit on a stock that they have sold short. A sell stop order is entered at a stop price below the current market price. Investors generally use a sell stop order to limit a loss or to protect a profit on a stock that they own.
Before using a stop order, investors should consider the following:
* short-term market fluctuations in a stocks price can activate a stop order, so a stop price should be selected carefully.
* The stop price is not the guaranteed execution price for a stop order. The stop price is a trigger that causes the stop order to become a market order. The execution price an investor receives for this market order can deviate significantly from the stop price in a fast-moving market where prices change rapidly. An investor can avoid the risk of a stop order executing at an unexpected price by placing a stop-limit order, but the limit price may prevent the order from being executed.
* For certain types of stocks, some brokerage firms have different standards for determining whether a stop price has been reached. For these stocks, some brokerage firms use only last-sale prices to trigger a stop order, while other firms use quotation prices. Investors should check with their brokerage firms to determine the specific rules that will apply to stop orders.
2. A stop-limit order is an order to buy or sell a stock that combines the features of a stop order and a limit order. Once the stop price is reached, a stop-limit order becomes a limit order that will be executed at a specified price (or better). The benefit of a stop-limit order is that the investor can control the price at which the order can be executed.
Before using a stop-limit order, investors should consider the following:
* As with all limit orders, a stop-limit order may not be executed if the stocks price moves away from the specified limit price, which may occur in a fast-moving market.
* Short-term market fluctuations in a stocks price can activate a stop-limit order, so stop and limit prices should be selected carefully.
* The stop price and the limit price for a stop-limit order do not have to be the same price. For example, a sell stop limit order with a stop price of $3.00 may have a limit price of $2.50. such an order would become an active limit order if market prices reach $3.00, although the order could only be executed at a price of $2.50 or better.
* For certain types of stocks, some brokerage firms have different standards for determining whether the stop price of a stop-limit order has been reached. For these stocks, some brokerage firms use only last-sale prices to trigger a stop-limit order, while other firms use quotation prices. Investors should check with their brokerage firms to determine the specific rules that will apply to stop-limit orders.
3. One Cancel Other order(OCO):
One Cancel Other order
The one cancels other order option allows you to place a pair of orders stipulating that if one order is executed fully or partially, then the other is automatically canceled. An OCO order combines a stop order with a limit order. This option allows you to place both take profit and stop loss targets for your position (only for limit orders).
Example: If the market price is 250 and the trader wants a stop order at 245 and a limit order at 260, then a OCO order may be appropriate. If the market reaches 245, the stop order will trigger a market order and cancel the limit order at 260. If the market reaches 260 before 245, the limit order will execute and cancel the stop order at 245.
Note: If you manually cancel one of the OCO orders; i.e., the stop or the limit, you must also manually cancel the other one. An OCO order is only automatically canceled if the other order is partially or fully executed by market price movement.
so now for every new type we should create a class:
1. stop-order:<br >
stop orders are like a market order with an activator price(we call it igniter price)
so we Inherit this class from Market order class and add new attr
1. stop-limit-order:<br >
stop limit orders are like a limit order with an activator price(we call it igniter price)
so we Inherit this class from Limit order class and add new attr
3. inherit from StopLimitOrder
after creating new classes,we need an orderbook to save the new orderbook in a arranged structure:
* we store them in rbtree(red-black tree) to make searching faster.
we implemented find, add and remove method for every new order type.
* order book manager:
it initializes bid and ask orderbooks.
```mermaid
graph TD
A[ENGINE] -->|initializes|B(orderbook manager)
A[ENGINE] -->|initializes|C(special orderbook manager)
B --> |initializes|D(ask orderbook)
B --> |initializes|E(bid orderbook)
C --> |initializes|F(ask special orderbook)
C --> |initializes|G(bid special orderbook)
D --> |initializes|H(limit orders)
D --> |initializes|I(market orders)
E --> |initializes|J(limit orders)
E --> |initializes|K(market orders)
F --> |initializes|L(oco orders)
F --> |initializes|M(stop limit orders)
F --> |initializes|N(stop orders)
G --> |initializes|O(oco orders)
G --> |initializes|P(stop limit orders)
G --> |initializes|Q(stop orders)
```

View File

@@ -0,0 +1,53 @@
# New order types
###### Sprint: 10
### Outcome:
Prepare the Peatio (structure and code) to support new order types<br />
the new order types are:
- **Stop** : the market order that is triggered by a specific price
- **Stop-Limit** : the limit order that is triggered by a specific price
- **OCO**: consist of two types: 1)limit 2)stop; each enters the matching stage, cancel another
### Implementation description:
#### branch :
orderType
#### Commit
361e4d99<br />
2b6390ee
#### File destination:
- {$Dena_path}/app/models/order.rb<br/>
- {$Dena_path}/db/migrate/20210815080757_add_new_order_types_to_orders.rb<br/>
- {$Dena_path}/app/api/v2/admin/orders.rb<br/>
- {$Dena_path}/app/api/v2/entities/order.rb<br/>
- {$Dena_path}/app/api/v2/management/entities/order.rb<br/>
- {$Dena_path}/app/api/v2/management/orders.rb<br/>
- {$Dena_path}/app/api/v2/market/named_params.rb<br/>
- {$Dena_path}/app/api/v2/market/orders.rb<br/>
- {$Dena_path}/app/api/v2/order_helpers.rb<br/>
- {$Dena_path}/app/jobs/cron/ticker.rb<br/>
- {$Dena_path}/app/models/order.rb<br/>
- {$Dena_path}/app/models/order_ask.rb<br/>
- {$Dena_path}/app/models/order_bid.rb<br/>
#### What did we implement:
we added three columns (`igniter_price`, `origin_type`, `relative_id`) to order table to support new types.
- `igniter_price`: use for trigger order when the market price achieve to it
- `origin_type`: use for keep the original type of order
- `relative_id`: use for link OSO orders together
There will be a new class called `Igniter`.<br />
This class is feed by the Ticker to know the moment price of the market.<br />
each time the market price will be the same with igniter-price of any special order,<br />
this class change the special-order to `limit` or `market` order. (So the past process will be repeated).<br />
also, if order type was OCO, in matching step if matched happened, the relative order will find by relative_id, and cancel it.<br />
this changing is happened by changing the value of `ord_type` to **limit** or **market**.<br />
but the value of `origin_type` remains without any changes, so we always know the original type of order.
##### note:
add a new step before the Matching step to prevent special orders to enter matching step.<br/>
We can name this stage: the Controlling

View File

@@ -0,0 +1,53 @@
# operation: accounting
###### Sprint: ?
### Outcome:
a simple information about operations.
#### File destination:
{$Dena_Path}/app/model/operations/
##### Doc
* Operation:
this is the base class for operations and subcategories Heir from it.
operation column:
1. reference: it has polymorphic for every type of references(for example trades or withdraws or deposit or ..)
2. currencies: code of currency
3. credit: plus funds
4. debit: minus funds
5. account
methods of operations were implemented in this class and subcategories only use them.
```mermaid
graph TD
A[operation] -->|inheritance| B(Expense)
A[operation] -->|inheritance| C(Asset)
A[operation] -->|inheritance| D(Liability)
A[operation] -->|inheritance| E(Revenue)
```
this chart showed inheritance structure of operation.
1. Expense:<br >
Expense is a income statement operation.
2. Asset<br >
is a balance sheet operation.every income/outcome of system store and controll by it.
3. Liability<br >
is a balance sheet operation and belongs to members and we manage members accounting things by it.
for example trades and deposit.
4. Revenue:<br >
is a income statement operation and we manage exchange revenue by it.
####SO:
* revenue --> revenue of exchange
* liability --> users accounting
* asset --> exchange assets
* expense --> ?

View File

@@ -0,0 +1,82 @@
# trading: trade executor
###### Sprint: ?
###DOC
* in case of reading first part processor or matching please skip this part.
for matching and executing orders openware creates a flow that manage by RabbitMQ and its consumers.
we have three consumers that works on trades:
1. order processor:<br >
does preliminary calculations and works on order like locking order<br >
2. matching:<br >
match orders and pass them to executor
3. trade executor:<br >
execute trades that matching creates
```mermaid
stateDiagram-v2
[*] --> API
API --> RabbitMQ
RabbitMQ --> OrderProcessor
OrderProcessor --> RabbitMQ
RabbitMQ --> Matching
Matching --> RabbitMQ
RabbitMQ --> Executor
Executor --> Notify
Notify --> [*]
```
#### Trade executor
##### what does trade executor do step by step:
1. it gets price and market and other informations
2. create_trade_and_strike_orders
1. get both orders
2. get both needed accounts
3. validate above informations
4. initialize new trade with above data
5. strike maker side
1. change order attr like volume,locked,...
2. unlocking funds and plus funds
2. check order fill
6. strike taker side
1. change order attr like volume,locked,...
2. check order fill
7. create operations and accountings recorde
1. record_liability_debit!
2. record_liability_credit!
3. record_liability_transfer!
4. record_revenues!
8. publish trade dependent on its state
```mermaid
graph TD
A[RabbitMQ] -->|submit payload| B(executor)
B --> |execute|C(get information about trade)
C --> D(get both orders)
D --> E(get both needed accounts)
E --> F(validation on datas)
F --> G(initialize new trade)
G --> H( maker side)
G --> I(taker side)
H --> J(striker)
I --> J
J -->K(calculate incomes and fees)
K --> L(update orders data like locked and volume,..)
L --> M(unlock funds and plus incomes)
M --> N{is order filled}
N --> |yes|O(change state to done)
O --> P(unlocked extra locked funds)
N -->|no and market order|Q(cancell order)
Q --> R(create operations record for cancellation)
R --> S(create operation records)
P --> S
S --> T(record_liability_debit, record_liability_credit, record_liability_transfer, record_revenues)
T --> U(save trade)
U --> V(publish trade)
```

View File

@@ -0,0 +1,73 @@
# trading: order matching
###### Sprint: ?
###DOC
* in case of reading first part processor please skip this part.
for matching and executing orders openware creates a flow that manage by RabbitMQ and its consumers.
we have three consumers that works on trades:
1. order processor:<br >
does preliminary calculations and works on order like locking order<br >
2. matching:<br >
match orders and pass them to executor
3. trade executor:<br >
execute trades that matching creates
```mermaid
stateDiagram-v2
[*] --> API
API --> RabbitMQ
RabbitMQ --> OrderProcessor
OrderProcessor --> RabbitMQ
RabbitMQ --> Matching
Matching --> RabbitMQ
RabbitMQ --> Executor
Executor --> Notify
Notify --> [*]
```
#### Order matching
##### what does order matching do step by step:
1. submit order ro engine
2. match method
1. get orderbooks
2. loop
1. is order filled?(all amount)
2. get top order of opposite order book(top means order with best price)
* for better and faster searching they use rbtree. for more information [click here](https://www.geeksforgeeks.org/red-black-tree-set-1-introduction-2/)
3. check can they create a trade
4. is trade valid?(trade validation):<br >
* not zero,calculation problems
5. fill both orders:<br >
* decrease order volume(if the opposite order is filled, we remove it from orderbook)
* filled order means that order completely get its needed volume
6. send to trade executor
```mermaid
graph TD
A[RabbitMQ] -->|submit payload| B(Matching)
B -->|submit engine|C(match method)
C --> D(get orderbooks)
D --> E(loop)
E --> F{order filled?}
F --> |yes|X(break)
F --> |no|G{opposit orderbook is blanked}
G --> |yes|H{is it limit order?}
H --> |yes|I(add to orderbook)
I --> X
H --> |no|J(cancel order)
J --> X
G --> |no|K(get top of opposit orderbook)
K --> L(make trade with top of opposit)
L --> |created trade|M{trade.blank?}
M --> |yes|H
M --> |no|N(validate trade)
N --> O(fill order)
O --> P(fill opposit order)
O --> |publish to executor|A
O --> E
X --> A
```

View File

@@ -0,0 +1,34 @@
# Order Creation: Api
### Outcome:
Users create sell or buy order.
### Implementation description:
#### Endpoints:
- POST {$domain}/api/v2/peatio/marker/orders/fiat
#### Params
- market
- side
- volume
- ord_type
#### File destination:
{$Dena_Path}/app/api/v2/market/orders.rb
```mermaid
sequenceDiagram
title Order Creation
User->>Ranj: market, side, volume, ord_type
Ranj->>Dena: POST: after client side checking
Dena->>Ranj: 4xx if lose any required parameters
Dena->>Ranj: 4xx if users level lower than the
Dena->>Dena: compute lock balance
Dena->>Dena: send order to the Order Processor queue
Dena->>Ranj: 2xx order record created
Ranj->>User: show The Order response
```

View File

@@ -0,0 +1,52 @@
# trading: order processor
###### Sprint: ?
###DOC
for matching and executing orders openware creates a flow that manage by RabbitMQ and its consumers.
we have three consumers that works on trades:
1. order processor:<br >
does preliminary calculations and works on order like locking order<br >
2. matching:<br >
match orders and pass them to executor
3. trade executor:<br >
execute trades that matching creates
```mermaid
stateDiagram-v2
[*] --> API
API --> RabbitMQ
RabbitMQ --> OrderProcessor
OrderProcessor --> RabbitMQ
RabbitMQ --> Matching
Matching --> RabbitMQ
RabbitMQ --> Executor
Executor --> Notify
Notify --> [*]
```
#### Order Processor
##### what does order processor do step by step:
1. initializing: submit all orders with pending state(take them to ram)
2. submit:<br >
1. it finds order by id with lockversion
2. check state of order
3. update locked and balance of account
4. submit operation and accounting
5. update order state to WAIT
6. enqueue in rabbit (pass orders to matching)
```mermaid
graph TD
A[api] -->|enque| B(RabbitMQ)
B --> C(order processor)
C --> |submit order in ram|D{check state}
D -->|pending| E[order locking]
D -->|else| B
E -->G[submit operation and accounting]
G --> F[update state to wait]
F --> |enque to matching| B
```

69
docs/zagros/referral.md Normal file
View File

@@ -0,0 +1,69 @@
# Market: referral
###### Sprint: ?
### Outcome:
users can invite other users.if an user sign up with another user invitation code, exchange gives inviter a bonus to encourage people to join our exchange.
bonus amount is a percent of trade fee.
#### File destination:
{$Dena_Path}/app/jobs/referral_bonus.rb
{$Dena_Path}/app/models/bonus.rb
#### Commits:
#### What did we implement:
first of we need a table to save bonuses.
we create bonus table.its columns are:
1. trade_id: foreign key to trade tables.this shows that this bonus was created from which trade.
2. sender_member_id: foreign key to members tables.this shows bonus was created from which member trade(invited memebr).
3. bonus_member_id: foreign key to members tables.this shows bonus was sent to which member(inviter member).
4. amount: amoutn of bonus
5. state: state of bonus { pending: 0, payed: 1, rejected: 2 }
* we have an validation on creating bonus for avoiding duplication and double paying.
```ruby
validates_uniqueness_of :trade, :scope => [:sender_member_id]
```
this means that can not create bonus with same trade **AND** same sender.
<br >
<br >
<br >
<br >
* we created a cron job that runs every 24 hour (we plan to run it in midnights to avoid putting pressure on server)
This is how it works:
1. select all last 24 hour revenues and process them in batch of 1000.
2. get them one by one and convert them to rial and multiply them with referral bonus percent.
3. create bonus, update users balance(with lock version) and create on revenue debit for accounting system(we cant lost money in system)
* all calculations and db updates that related about money(critical calculations) are in transaction so if one of them blocked or rejected all changes rollbacked .
```mermaid
graph TD
title:referral_job
A[loop:batch 1000] -->|1000 of last 24h| B(one of revenue)
B -->|revenue| D{has referral}
D -->|no| B
D -->|yes| F{is in rial}
F -->|yes| I
F -->|no| H[convert to irt]
H --> I[calculation bonus amount]
I --> J[changes balance]
J --> K[create bonus and accounting things]
K --> L{error happend?}
L --> |yes| M[roll back everything]
L --> |no| P
M --> O[create bonus with pending state]
O --> P{1000 ended?}
P -->|yes| A
P -->|no| B
```

View File

@@ -0,0 +1,53 @@
# Market: dynamic trade fee
###### Sprint: ?
### Outcome:
in every trade exchange take some fee from users as revenue.these fees are some percentages from all trade value.
these percentages must be dynamic toward last thirty days trades amount.
exchange sets some levels and amount of them. if users reach every target, exchange change the fee level of them.
#### File destination:
{$Dena_Path}/app/models/trade.rb
{$Dena_Path}/app/models/member.rb
#### Commits:
#### What did we implement:
* trades are executed in different markets and every market has different quote currency.
for simplifying calculation of the last thirty days trades amount we create new call back(before save) to calculate last thirty days trades amount in irt and save them in new column.
```def rial_total!```
this function has to case:
1. quote currency is irt: total saved
2. quote currency is usdt: first get price_now of tether and calculate rial amount(total value of trade in irt)
* before creating and submitting orders, fee level of user Determined and applied on calculations.
this calculations runs on order creation validations.
```mermaid
graph TD
A[API] -->|order attrs| B(order creation)
B --> C{calculating last 30 days amount}
C -->|touch new target| D[update its group]
C -->|no changes| E[no change in group]
D --> F[order created]
E --> F
F --> G[ ___MATCH ENGINE___]
G --> |matched with another order|H[create trade]
H --> I[calculate irt based amount]
I --> J[save trade]
```

View File

@@ -0,0 +1,52 @@
# Vandar Service
###### Sprint: 5
### Outcome:
users can deposit fiat and withdraw fiat by connection to the Vandar
### Implementation description:
#### File destination:
{$Dena_Path}/app/services/vandar_service.rb<br />
{$Dena_Path}/app/api/v2/account/deposits.rb<br />
{$Dena_Path}/app/api/v2/account/withdraw.rb<br />
{$Dena_Path}/app/models/withdraw.rb<br />
{$Dena_Path}/app/models/deposit.rb<br />
#### Commits:
3b189b07<br/>
2cd9b4ad<br/>
f83585dd<br/>
b832b0fb
#### What did we implement:
in the Opendax, there is no way to deposit or withdraw for fiat,
so we use the Vandar as a third party to connect real banks for deposit and withdraws.<br />
for talking with The Vandar, we implemented a new service named VandarService (vandar_service.rb).<br />
VandarService has four part, Login, Deposit, Withdraw, Transaction
##### login part:
this part is used for login in the Vandar with mobile and password that these two must exist in the config file<br />
this part has a `login` method that automatically calls when creating object from this service
##### deposit part:
this part is used for doing deposits<br />
this part has a three methods:<br />
-`generate_token`: use for generate unique Bank Gateway token
-`transaction`: use for finding specific deposit in the Vandar
-`verify`: use for verify specific deposit in the Vandar
##### withdraw part:
this part is used for doing withdraws<br />
this part has a four methods:<br />
-`list_withdraw`: use for listing withdraws (never use in process)
-`info_withdraw`: use for get specific withdraw information from the Vandar
-`delete_withdraw`: use for delete specific withdraw in the Vandar (never use in process)
##### transaction part:
- `list_transactions`: use for listing transaction with fromDate and toDate as parameters (use it in withdraw Job)
#### note:
we use Faraday Gem to send request to vandar

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

View File

@@ -0,0 +1,43 @@
# Wallet types
![image](wallets.jpeg)
## 1. Deposit
This wallet is the first place to store users' property.<br />
we generated new addresses from this wallet for users,
so users can send their crypto coin to these addresses.
these addresses are keeping in local DB.<br/>
so the blockchain daemon fetch stream block and recognizes a relevant transaction by these addresses
## 2. Fee
Use this wallet for calculate and pays the fee for (ERC20 case)
![image](fee_wallet.jpeg)
## 3.Hot 4.Warm 5.Cold
#### Deposit process
If the deposit equal or higher than 'Min collection amount' the system initialise a deposit collecting process to move funds from the deposit wallet to exchange wallet/wallets ('Hot', 'Warm' or 'Cold').<br/>
That process requires a few checks: <br />
- If a sum of the deposit + 'Hot wallet' balance lower than 'Max balance' of 'Hot wallet' then the system moves the deposit to 'Hot wallet'
- If a sum of the deposit + 'Hot wallet' balance is higher than 'Max balance' of 'Hot wallet' then the system checks next conditions.- If a sum of the deposit + 'Hot wallet' balance + 'Warm wallet' balance lower than a sum of "hot" and "warm" wallets max balances then the system checks next conditions.
- If 'Hot wallet' reached max balance the system moves deposit to 'Warm wallet'
- If 'Hot wallet' hasn't reached max balance the system divides the deposit between 'Hot wallet' and 'Warm wallet'.
- If a sum of the deposit + 'Hot wallet' balance + 'Warm wallet' balance higher than a sum of "hot" and "warm" wallets max balances then the system does next checks:
- If 'Warm wallet' reached max balance the system moves deposit to 'Cold wallet'
- If 'Warm wallet' hasn't reached max balance the system divides the deposit between 'Warm wallet' and 'Cold wallet'.
#### Withdraw process
- User creates a withdrawal request.
- System checks if the user has enough funds to proceed withdrawal transaction. If the user doesn't have enough funds, the system reject to create withdrawal request.<br/>
If the user has enough funds, the system accepts that request and do the next checks.
- If the user hasn't reached any withdrawal limits, the system process the withdrawal request automatically from 'Hot wallet'. If 'Hot wallet' doesn't have enough funds to process the withdrawal request the system throw error.<br/>
In this situation, the admin needs to replenish 'Hot wallet'.
- If the user reached at least one of withdrawal limits (24h or 72h) the system accepting that request but doesn't process it automatically. <br/>
Admin can manually reject or process that withdrawal request from 'Hot wallet'.
- Withdrawal request for a big amount can be processed manually by the admin. Big withdrawals should be processed outside the system, from 'Warm wallet'.<br/>
When the admin have generated and signed withdrawal transaction he has to propagate that transaction to the network. After transaction propagation admin has to upload TxId into the admin panel.<br />
If there are not enough funds in 'Warm wallet' to process the withdrawal request the admin needs to replenish 'Warm wallet' from 'Cold wallet' (transaction signing should be done offline).
![image](peatio_wallets.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

View File

@@ -0,0 +1,53 @@
# KYC withdraw, deposit limitation
###### Sprint: 4
[first read](../../../docs/peatio/withdraw_limits.md)
### Outcome:
each user's withdrawing and deposit for executing must not be reached to daily or monthly limitation
### Implementation description:
#### File destination:
{$Dena_Path}/app/models/deposit.rb<br />
{$Dena_Path}/app/models/withdraw.rb<br />
{$Dena_Path}/app/models/deposit_limit.rb<br />
{$Dena_Path}/app/models/withdraw_limit.rb<br />
{$Dena_Path}/app/models/withdraws/fiat.rb<br />
{$Dena_Path}/app/models/deposits/fiat.rb<br />
{$Dena_Path}/db/migrate/20210504102945_add_kind_to_withdraw_limits.rb<br />
{$Dena_Path}/db/migrate/20210504102945_add_kind_to_withdraw_limits.rb<br />
#### Commits:
7d4bd576<br/>
d436176b
#### What did we implement:
in the Opendax, withdrawal limitation was handled by a model named `WithdrawLimit`,
but for deposit limitation, there was no way.<br />
so by following existence rules, we create a new model and called it `DepositLimit` with the same columns,
and those columns are :
| Name | Type | Description |<br/>
| ---- | ---- | ----------- |<br/>
| id | integer | Unique table identifier in database. |<br/>
| group | string | Member group for define limits. |<br/>
| kyc_level | string | KYC level for define limits.|<br/>
| limit_24_hour | double | 24 hours limit. |<br/>
| limit_1_month | double | 1 month limit. |<br/>
and also we added a new column to the mentioned models by name: `kind` to support `fiat` and `coin` limitation<br/>
| Name | Type | Description |<br/>
| ---- | ---- | ----------- |<br/>
| kind | integer | Withdraw or Deposit kind (coin or fiat).|<br/>
before creation a withdrawal or deposit record by the user,
we implemented a new function called `verify_limits` that check the user reached limitation or not,
then permit the new withdraw or deposit record to be created.
### TODO
implement admin side include APIs (tower panel) for deposit limitation part

View File

@@ -0,0 +1,49 @@
# Withdraw: Coin
###### Sprint: 7
### Outcome:
Users can do coin withdrawal from any wallet to favorite address
### Implementation description:
#### Endpoints:
POST {$domain}/api/v2/peatio/account/withdraws
#### File destination:
{$Dena_Path}/app/api/v2/account/withdraws.rb
#### Commits:
016303d1<br />
cc565d9e<br />
12322261<br />
#### What did we implement:
we add controlling step before withdraw creation, so at first check 2fa (if was enabled),<br />
the check auth code that was sent to the email
```mermaid
sequenceDiagram
Title: Withdraw Coin
User->>Ranj:select favorite beneficiary
Ranj->>User:Ask OTP code for confirming
User-->>Ranj:if OTP code not received, try for resend after 120 seconds
Ranj-->>Dena: Ask for sending OTP code again
Dena-->>User:2xx send otp to his or her email
note over User,Ranj:note parameter is optioanl
User->>Ranj:otp, beneficiary_id, currency, amount, **note**
Ranj->>Dena:POST: after client side checking
Dena->>Ranj:4xx if lose any required parameters
Dena->>Ranj:4xx if the config variable: **ENABLE_ACCOUNT_WITHDRAWAL_API** is FALSE
Dena->>Ranj:4xx if enter 2fa code wrong (will be check if 2fa is activated before)
Dena->>Ranj:4xx if OTP code expired
Dena->>Ranj:4xx if beneficiary is not active
Dena->>Ranj:4xx if withdrawal is disabled for the currency
note over Dena,Blockchain:The Blockchain service has own documentation
note over Dena,Blockchain:The Blockchain service trigged by hook method in withdraw model
Dena->>Blockchain:coin withdraw record created and balance locked
Dena->>Ranj:2xx coin withdraw created
Ranj->>User: notify user that new withdraw created
```

View File

@@ -0,0 +1,57 @@
# Withdraw: Fiat
###### Sprint: 5
### Outcome:
Users can do fiat withdrawal with the Help of the Vandar service.
### Implementation description:
#### Endpoints:
POST {$domain}/api/v2/peatio/account/withdraws/fiat <br/>
POST {$domain}/api/v2/peatio/account/withdraws/confirm
#### File destination:
{$Dena_Path}/app/api/v2/account/withdraws.rb
#### Commits:
2cd9b4ad<br />
cc7ce09c<br />
2826a52c<br />
b9154ef8<br />
79d4b137<br />
807f350b<br />
638b493c<br />
7769e86a<br />
14fdfd2a<br />
#### What did we implement:
we implemented a new client route for user, to they can withdraw their money after entering valid 2fa and also,
auth code that was sent to the email
```mermaid
sequenceDiagram
Title: Withdraw Fiat
note over User,Ranj:note parameter is optioanl
User->>Ranj:amount, iban, currency, **note**
Ranj->>Dena:POST: after client side checking
Dena->>Ranj:4xx if lose any required parameters
note over Dena,Vandar:The Vandar service has own documentation
Dena->>Ranj:4xx if the config variable: **ENABLE_ACCOUNT_WITHDRAWAL_API** is FALSE
Dena->>Ranj:4xx if enter 2fa code wrong (will be check if 2fa is activated before)
Dena->>Ranj:4xx if entered IBAN not exist in current user valid IBAN list
Dena->>User:2xx withdraw record created and send otp to his or her mail
Ranj->>User:Ask OTP code for confirming
User-->>Ranj:if OTP code not received, try for resend after 120 seconds
Ranj-->>Dena: Ask for sending OTP code again
Dena-->>User:2xx send otp to his or her email
User->>Ranj: enter OTP code
Ranj->>Dena:Post : OTP code for checking
Dena->>Ranj:4xx if OTP code expired
Dena->>Vandar:2xx account balance locked
Dena->>Vandar:POST track_id, amount, IBAN
Vandar->>Dena:200 new withdraw with transaction_id was created for sending the Bank
Dena->>Ranj:withdraw will be rejected if the status of the Vandar response is false \n or withdraw will be confirmed and updated transaction_id if the status of the response is true
Ranj->>User: show The vandar response
```

View File

@@ -0,0 +1,58 @@
# Blockchain Withdraw: Coin
###### Sprint: 7
### Outcome:
Users can do coin withdrawal from any wallet to favorite address
#### File destination:
- {$Dena_Path}/app/model/withdraw.rb
- {$Dena_Path}/app/workers/amqp/withdraw_coin.rb
### Implementation description:
after withdraw was created by the user through the API,
the hooked method will be called and send the hash message (withdraw data) to RabbitMq relevant queue.<br />
the class is responsible to handle the hash message is: `WithdrawCoin`
1- finding the Withdraw by the id in the hash message if not, an error will be logged that not found a record in DB and exit
2- locking the Withdraw
3- check state of the Withdraw is processing, if not, an error will be logged and exit
4- check destination address was present, if not, an error will be logged, the Withdraw will be failed and exit
5- logging warning message that withdraw is ready for sending to blockchain
6- find an active hot wallet, if not, an error will be logged, the Withdraw will be skipped, and exit
7- check the balance of the active hot wallet, if not appropriate log error, skip the Withdraw and exit
8- create an object from WalletService by the active hot wallet
9- **WalletService** call `build_withdrawal!` for the withdraw and return transaction
10- the `txid` of the Withdraw being update by the Hash of the transaction
11- changing withdraw the state from `processing` to `confirming` with `dispatch` function
12- save the Withdraw in DB
```mermaid
graph TD
A[API] --> |post request| B[withdraw model]
B --> |hooked method| C(RabbitMq)
D(withdraw coin) --> |hash message in queue| C
D --> E((WalletService))
```
#### WalletService
this class using as a middleman for connecting to every coin wallet.<br />
In the time of creation object, the adapter (the hand of this class to talk the crypto coin wallet) receives its config.<br />
The aim of WalletService class is to union and structurize all crypto coin wallets implemented in the Peatio.<br />
##### build_withdrawal! function
this method create transaction on blockchain by the help of adapter and specific its config
```mermaid
graph LR
A(Peatio) -->|Blockchain stuffs| B[BlockchainService using adapter]
A --> |Wallet Deposit/Withdraw| C[WalletService using adapter]
B --> |Blockchain stuffs| D((Btc Blockchain))
B --> |Blockchain stuffs| E((Eth Blockchain))
B --> |Blockchain stuffs| F((...))
B --> A
C --> |Wallet Deposit/Withdraw| G((Btc Wallet))
C --> |Wallet Deposit/Withdraw| H((Eth Wallet))
C --> |Wallet Deposit/Withdraw| I((...))
C --> A
```