From e0a3846848c27c755fb6d41debea890d0006accb Mon Sep 17 00:00:00 2001 From: Pan Xiong Date: Thu, 30 Nov 2023 21:26:21 +1100 Subject: [PATCH] Add current price to open spot orders --- app/jobs/get_binance_open_orders_job.rb | 22 +++++++++++++++++++++- app/models/open_spot_order.rb | 7 +++++++ app/views/page/open_spot_orders.html.erb | 4 ++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/jobs/get_binance_open_orders_job.rb b/app/jobs/get_binance_open_orders_job.rb index 7cdbee1..aed713c 100644 --- a/app/jobs/get_binance_open_orders_job.rb +++ b/app/jobs/get_binance_open_orders_job.rb @@ -41,7 +41,10 @@ def get_spot_orders price = open_order[:price].to_f qty = open_order[:origQty].to_f amount = price * qty - order = OpenSpotOrder.where(order_id: open_order[:orderId], symbol: open_order[:symbol]).first_or_initialize + symbol = open_order[:symbol] + from_symbol = symbol.split('USDT')[0] + get_current_price(symbol, from_symbol) + order = OpenSpotOrder.where(order_id: open_order[:orderId], symbol: symbol).first_or_initialize order.update( status: open_order[:status], price: price, @@ -59,4 +62,21 @@ def get_spot_orders OpenSpotOrder.where.not(symbol: symbols).delete_all end end + + def get_current_price(symbol, from_symbol) + price = $redis.get("binance_spot_price_#{symbol}").to_f + if price == 0 + price = BinanceSpotsService.new(user_id: user_id).get_price(symbol)[:price].to_f rescue 0 + price = get_coin_price(from_symbol) if price.zero? + $redis.set("binance_spot_price_#{symbol}", price, ex: 2.hours) + end + end + + def get_coin_price(symbol) + date = Date.yesterday + url = ENV['COIN_ELITE_URL'] + "/api/coins/history_price?symbol=#{symbol}&from_date=#{date}&to_date=#{date}" + response = RestClient.get(url) + data = JSON.parse(response.body) + data['result'].values[0].to_f rescue nil + end end \ No newline at end of file diff --git a/app/models/open_spot_order.rb b/app/models/open_spot_order.rb index e0968c6..d083125 100644 --- a/app/models/open_spot_order.rb +++ b/app/models/open_spot_order.rb @@ -1,2 +1,9 @@ class OpenSpotOrder < ApplicationRecord + def current_price + $redis.get("binance_spot_price_#{symbol}").to_f + end + + def margin_rate + current_price.zero? ? 0 : ((price - current_price) / current_price) * 100 + end end diff --git a/app/views/page/open_spot_orders.html.erb b/app/views/page/open_spot_orders.html.erb index c20e9fd..0f37da1 100644 --- a/app/views/page/open_spot_orders.html.erb +++ b/app/views/page/open_spot_orders.html.erb @@ -21,6 +21,8 @@ 币种 买卖类别 委托价 + 当前价 + 委托家和当前价的比例 委托数量 成交数量 委托金额 @@ -35,6 +37,8 @@ <%= order.symbol %> <%= I18n.t("views.trading.#{order.trade_type}") %> <%= order.price.round(4) %> + <%= order.current_price.round(4) %> + <%= order.margin_rate.round(2) %>% <%= order.orig_qty.round(4) %> <%= order.executed_qty.round(4) %> <%= order.amount.round(4) %>