Skip to content

Commit

Permalink
Add binance positions and update funding fee histories
Browse files Browse the repository at this point in the history
  • Loading branch information
pan-xiong committed Oct 21, 2023
1 parent eddf161 commit 79fc915
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 15 deletions.
27 changes: 21 additions & 6 deletions app/jobs/get_funding_fee_histories_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ def perform(sync_ranking: false)
symbol = source == 'okx' ? ticker['instId'] : ticker['symbol']
result.push({
symbol: ticker['symbol'],
rate: get_rate(symbol, source, Date.today, get_latest: true)
rate: get_rate(symbol, source, Date.today)
})
end

$redis.set('top_3_symbol_funding_rates', result.to_json)
else
date = Date.yesterday
@okx_fee_list = OkxFuturesService.new.get_funding_fee_histories['data']

UserPosition.available.where(user_id: nil).each do |up|
generate_history(up, date)
end
Expand All @@ -30,22 +32,35 @@ def perform(sync_ranking: false)
end

def generate_history(up, date)
rate = get_rate(up.origin_symbol, up.source, date)
funding_fee = get_fee(up.origin_symbol, up.source, date)
SnapshotPosition.joins(:snapshot_info).where(snapshot_info: { user_id: up.user_id }, origin_symbol: up.origin_symbol, event_date: date, source: up.source).each do |snapshot|
ffh = FundingFeeHistory.where(origin_symbol: snapshot.origin_symbol, event_date: date, source: snapshot.source, user_id: up.user_id, trade_type: up.trade_type).first_or_initialize
ffh.update(rate: rate, amount: rate * up.amount * 3, snapshot_position_id: snapshot&.id)
ffh.update(amount: funding_fee, snapshot_position_id: snapshot&.id)
end
end

def get_fee(symbol, source, date)
if source == 'binance'
fee_list = BinanceFuturesService.new.get_funding_fee_histories(symbol, date.strftime('%Q'))
daily_fees = fee_list.select{|r| Time.at(r['time']/1000).to_date == date}
daily_fees.sum{|f| f['income'].to_f}
elsif source == 'okx'
daily_fees = @okx_fee_list.select{|r| Time.at(r['ts'].to_i/1000).to_date == date && r['instId'] == symbol}
daily_fees.sum{|f| f['pnl'].to_f}
else
0
end
end

def get_rate(symbol, source, date, get_latest: false)
def get_rate(symbol, source, date)
if source == 'binance'
rate_list = BinanceFuturesService.new.get_funding_rate(symbol, date.strftime('%Q'))
daily_rates = rate_list.select{|r| Time.at(r['fundingTime']/1000).to_date == date}
get_latest ? daily_rates.last['fundingRate'].to_f : daily_rates.sum{|r| r['fundingRate'].to_f} / 3
daily_rates.last['fundingRate'].to_f
elsif source == 'okx'
rate_list = OkxFuturesService.new.get_funding_rate(symbol, date.strftime('%Q'))
daily_rates = rate_list['data'].select{|r| Time.at(r['fundingTime'].to_f/1000).to_date == date}
get_latest ? daily_rates.last['realizedRate'].to_f : daily_rates.sum{|r| r['realizedRate'].to_f} / 3
daily_rates.last['realizedRate'].to_f
else
0
end
Expand Down
19 changes: 11 additions & 8 deletions app/jobs/notify_new_symbol_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ def perform
end

def check_symbol_from_api
symbols = BinanceFuturesService.new.get_ticker_price.map{|x| x['symbol']} rescue []
return if symbols.empty?
data = BinanceFuturesService.new.get_ticker_price rescue nil
return if data.nil?

redis_key = 'binance_futures_symbols'
prev_symbols = JSON.parse($redis.get(redis_key)) rescue []
diff_symbols = symbols - prev_symbols
$redis.set(redis_key, symbols)
SlackService.send_notification(nil, format_api_blocks(diff_symbols)) if diff_symbols.any?
symbols = []
data.each do |d|
bp = BinancePosition.where(symbol: d['symbol']).first_or_initialize
symbols.push(bp.symbol) if bp.new_record?
bp.update(price: d[:price])
end

SlackService.send_notification(nil, format_api_blocks(symbols)) if symbols.any?
end

def format_notice_blocks(msg)
Expand All @@ -37,7 +40,7 @@ def format_api_blocks(symbols)
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*币安合约API新增币种: #{symbols.join(", ")}, 共#{symbols.length}个*"
"text": "*币安合约API新增币种: #{symbols.join(", ")}, 共 #{symbols.length}个*"
}
}
]
Expand Down
2 changes: 2 additions & 0 deletions app/models/binance_position.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class BinancePosition < ApplicationRecord
end
6 changes: 6 additions & 0 deletions app/services/binance_futures_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ def get_taker_long_short_ratio(symbol)
JSON.parse(response).last
end

def get_funding_fee_histories(symbol, start_time)
url = BASE_URL + "/fapi/v1/income?"
payload = {symbol: symbol, incomeType: 'FUNDING_FEE', timestamp: get_timestamp, startTime: start_time, limit: 1000}
do_request("get", url, payload)
end

private
def do_request(method, url, payload)
sign = signed_data(build_query(payload))
Expand Down
10 changes: 10 additions & 0 deletions app/services/okx_futures_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ def get_funding_rate(symbol, before=nil)
end
end

def get_funding_fee_histories(end_at=nil)
begin
request_path = "/api/v5/account/bills-archive?instType=SWAP&type=8"
request_path += "&end=#{end_at}" if end_at
do_request("get", request_path)
rescue => e
format_error_msg(e)
end
end

private
def do_request(method, request_path)
url = BASE_URL + request_path
Expand Down
10 changes: 10 additions & 0 deletions db/migrate/20231021091525_create_binance_positions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class CreateBinancePositions < ActiveRecord::Migration[6.1]
def change
create_table :binance_positions do |t|
t.string :symbol
t.decimal :price

t.timestamps
end
end
end
9 changes: 8 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions spec/factories/binance_positions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
FactoryBot.define do
factory :binance_position do
symbol { 'BTCUSDT' }
price { 1 }
end
end
9 changes: 9 additions & 0 deletions spec/models/binance_position_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
require 'rails_helper'

RSpec.describe BinancePosition, type: :model do
let(:binance_position) { create(:binance_position) }

it "have a valid factory" do
expect(binance_position).to be_valid
end
end

0 comments on commit 79fc915

Please sign in to comment.