replace get_ticker with get_orderbook

This commit is contained in:
gcarq 2017-10-13 21:09:55 +02:00
parent b3ed0151f0
commit 93b729a5d5
5 changed files with 37 additions and 25 deletions

View File

@ -1,6 +1,6 @@
import enum
import logging
from typing import List
from typing import List, Optional, Dict
import arrow
@ -85,8 +85,8 @@ def get_balance(currency: str) -> float:
return EXCHANGE.get_balance(currency)
def get_ticker(pair: str) -> dict:
return EXCHANGE.get_ticker(pair)
def get_orderbook(pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]:
return EXCHANGE.get_orderbook(pair, top_most)
def get_ticker_history(pair: str, minimum_date: arrow.Arrow):

View File

@ -1,5 +1,5 @@
import logging
from typing import List, Optional
from typing import List, Optional, Dict
import arrow
from bittrex.bittrex import Bittrex as _Bittrex, API_V2_0
@ -56,14 +56,13 @@ class Bittrex(Exchange):
raise RuntimeError('{}: {}'.format(self.name.upper(), data['message']))
return float(data['result']['Balance'] or 0.0)
def get_ticker(self, pair: str) -> dict:
data = _API.get_ticker(pair.replace('_', '-'))
def get_orderbook(self, pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]:
data = _API.get_orderbook(pair.replace('_', '-'))
if not data['success']:
raise RuntimeError('{}: {}'.format(self.name.upper(), data['message']))
return {
'bid': float(data['result']['Bid']),
'ask': float(data['result']['Ask']),
'last': float(data['result']['Last']),
'bid': data['result']['buy'][:top_most],
'ask': data['result']['sell'][:top_most],
}
def get_ticker_history(self, pair: str, minimum_date: Optional[arrow.Arrow] = None):

View File

@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
from typing import List, Optional
from typing import List, Optional, Dict
import arrow
@ -50,14 +50,26 @@ class Exchange(ABC):
"""
@abstractmethod
def get_ticker(self, pair: str) -> dict:
def get_orderbook(self, pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]:
"""
Gets ticker for given pair.
Gets orderbook for given pair.
:param pair: Pair as str, format: BTC_ETC
:param top_most: only return n top_most bids/sells (optional)
:return: dict, format: {
'bid': float,
'ask': float,
'last': float
'bid': [
{
'Quantity': float,
'Rate': float,
},
...
],
'ask': [
{
'Quantity': float,
'Rate': float,
},
...
]
}
"""

View File

@ -5,7 +5,7 @@ import logging
import time
import traceback
from datetime import datetime
from typing import Dict, Optional
from typing import Dict, Optional, List
from jsonschema import validate
@ -134,7 +134,7 @@ def handle_trade(trade: Trade) -> None:
logger.debug('Handling open trade %s ...', trade)
current_rate = exchange.get_ticker(trade.pair)['bid']
current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate']
if should_sell(trade, current_rate, datetime.utcnow()):
execute_sell(trade, current_rate)
return
@ -143,12 +143,13 @@ def handle_trade(trade: Trade) -> None:
logger.exception('Unable to handle open order')
def get_target_bid(ticker: Dict[str, float]) -> float:
def get_target_bid(ticker: Dict[str, List[Dict]]) -> float:
""" Calculates bid target between current ask price and last price """
if ticker['ask'] < ticker['last']:
return ticker['ask']
# TODO: refactor this
ask = ticker['ask'][0]['Rate']
bid = ticker['bid'][0]['Rate']
balance = _CONF['bid_strategy']['ask_last_balance']
return ticker['ask'] + balance * (ticker['last'] - ticker['ask'])
return ask + balance * (bid - ask)
def create_trade(stake_amount: float) -> Optional[Trade]:
@ -181,7 +182,7 @@ def create_trade(stake_amount: float) -> Optional[Trade]:
else:
return None
open_rate = get_target_bid(exchange.get_ticker(pair))
open_rate = get_target_bid(exchange.get_orderbook(pair, top_most=1))
amount = stake_amount / open_rate
order_id = exchange.buy(pair, open_rate, amount)

View File

@ -99,7 +99,7 @@ def _status(bot: Bot, update: Update) -> None:
else:
for trade in trades:
# calculate profit and send message to user
current_rate = exchange.get_ticker(trade.pair)['bid']
current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate']
current_profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate)
orders = exchange.get_open_orders(trade.pair)
orders = [o for o in orders if o['id'] == trade.open_order_id]
@ -156,7 +156,7 @@ def _profit(bot: Bot, update: Update) -> None:
profit = trade.close_profit
else:
# Get current rate
current_rate = exchange.get_ticker(trade.pair)['bid']
current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate']
profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate)
profit_amounts.append((profit / 100) * trade.stake_amount)
@ -250,7 +250,7 @@ def _forcesell(bot: Bot, update: Update) -> None:
send_msg('There is no open trade with ID: `{}`'.format(trade_id))
return
# Get current rate
current_rate = exchange.get_ticker(trade.pair)['bid']
current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate']
# Get available balance
currency = trade.pair.split('_')[1]
balance = exchange.get_balance(currency)