コード例 #1
0
 def getPublicAPI(self):
     while (1):
         try:
             self.zaif = ZaifPublicApi()
             break
         except:
             time.sleep(1)
コード例 #2
0
ファイル: app.py プロジェクト: naoland/nemlog-55771
def last_price(pair):
    """指定した通貨ペア(xem_jpyなど)の最終価格を表示します。"""
    zaif = ZaifPublicApi()
    result = zaif.last_price(pair)
    print(result)
    return template("<h1>{{pair}} 最終価格: {{result}}</h1>",
                    pair=pair,
                    result=result["last_price"])
コード例 #3
0
ファイル: exporter.py プロジェクト: tetocode/zaifexport
 def __init__(self, api_key: str, api_secret: str,
              wait_interval: float,
              limit: int,
              cache_limit: int,
              currencies: Optional[List[str]]):
     self.public_api = ZaifPublicApi()
     self.trade_api = ZaifTradeApi(api_key, api_secret)
     self.futures_public_api = ZaifFuturesPublicApi()
     self.futures_trade_api = ZaifLeverageTradeApi(api_key, api_secret)
     self._wait_interval = wait_interval
     self._limit = limit
     self._cache_limit = cache_limit
     if currencies:
         currencies = [x.upper() for x in currencies]
     self._currencies = currencies
コード例 #4
0
ファイル: backtest.py プロジェクト: mainyaa/bitmech
 def load_zaif_server():
     from zaifapi import ZaifPublicApi
     zaif = ZaifPublicApi()
     trade = zaif.trades(currency_pair='btc_jpy', limit=200000)
     return trade
コード例 #5
0
from zaifapi import ZaifPublicApi
import json
import requests
import wikipedia
import random
import csv
import datetime
import urllib
import urllib3.request
from bs4 import BeautifulSoup
import lxml
import sys
import codecs
import time

zaif = ZaifPublicApi()

client = discord.Client()

now = time.ctime()
cnvtime = time.strptime(now)

jsopen1 = open("token.json")
jsload1 = json.load(jsopen1)
token = jsload1['bot']['token']

BOT_TOKEN = token


@client.event
async def on_ready():
コード例 #6
0
ファイル: test_public_api.py プロジェクト: techbureau/zaifapi
 def setUpClass(cls):
     cls.api = ZaifPublicApi()
     cls.api._url._api_name = "test_public"
コード例 #7
0
ファイル: main.py プロジェクト: tosmori/Zaif
# -*- coding: utf-8 -*-

from zaifapi import ZaifPublicApi  # Zaifが公開している認証情報が要らないAPIを実行するクラス
from pprint import pprint  # 表示用(jsonをきれいに表示してくれる)

if __name__ == '__main__':
    zaif = ZaifPublicApi()

    print('---last_price : 終値--')
    pprint(zaif.last_price('btc_jpy'))

    print('---ticker : ティッカー(集計情報取得)--')
    pprint(zaif.ticker('btc_jpy'))

    print('---trades : 全ての取引履歴--')
    print('取得件数:' + str(len(zaif.trades('btc_jpy'))))
    pprint(zaif.trades('btc_jpy'))

    print('---depth : 板情報--')
    print('取得件数[買い]:' + str(len(zaif.depth('btc_jpy')['asks'])))
    print('取得件数[売り]:' + str(len(zaif.depth('btc_jpy')['bids'])))
    pprint(zaif.depth('btc_jpy'))

    print('---currency_pairs : trade_history等で利用可能な通貨ペア情報--')
    pprint(zaif.currency_pairs('btc_jpy'))

    print('---currencies : deposit_history等で利用可能な通貨情報--')
    pprint(zaif.currencies('all'))
コード例 #8
0
class EXCaccess:
    def __init__(self):
        self.investment = 10000  # 投資制限額
        # 予想利益額の閾値(閾値以上で注文)========================
        self.threshold_jpy_btc_mona = 300
        self.threshold_jpy_btc_bch = 150
        self.threshold_jpy_btc_xem = 150
        self.threshold_jpy_btc_eth = 150

        # 手数料 ( % )
        self.fee_BTC_JPY = 0
        self.fee_MONA_BTC = 0.1
        self.fee_MONA_JPY = 0.1
        self.fee_BCH_BTC = 0.3
        self.fee_BCH_JPY = 0.3
        self.fee_XEM_BTC = 0.1
        self.fee_XEM_JPY = 0.1
        self.fee_ETH_BTC = 0.1
        self.fee_ETH_JPY = 0.1

        # 注文確認の手がかりとして注文に付けるコメント
        self.order_comment = 'AutoTA'
        # API用キーの読み込み
        f = open('key_secret.txt', 'r')  # 本番用
        # f = open('test_keys.txt', 'r')  # テスト用
        txt = f.read()
        f.close()
        data = txt.split('\n')
        self.key = data[0]
        self.secret = data[1]

    def createErrorLog(self, locate: str):
        now = datetime.datetime.now()
        Path = 'error.log'
        with open(Path, 'a', newline='', encoding='shift-jis') as f:
            f.write('=====================================\n')
            f.write(str(now))
            f.write(locate)
            traceback.print_exc(file=f)

    # 公開情報に接続
    def getPublicAPI(self):
        while (1):
            try:
                self.zaif = ZaifPublicApi()
                break
            except:
                time.sleep(1)

    # 個人の情報に接続
    def getPrivateAPI(self):
        while (1):
            try:
                self.zaifp = ZaifTradeApi(self.key, self.secret)
                break
            except:
                time.sleep(1)

    # 余力額取得
    def getFunds(self):
        self.getPrivateAPI()
        while (1):
            try:
                result = self.zaifp.get_info2()['funds']
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getFunds')
                time.sleep(1)
        return result

    # 各通貨ペアの相場から買い気配値と売り気配値の中間値を返す
    # 公開情報の.currency_pairsで取得できるaux_unit_step(取引単価?)
    # BTC/JPY:5.0
    # MONA/BTC:0.00000001
    # MONA/JPY:0.1
    # BCH/BTC:0.0001
    # BCH/JPY:5.0
    # XEM/BTC:0.00000001
    # XEM/JPY:0.0001
    # ETH/BTC:0.0001
    # ETH/JPY:5.0
    # ====================================================
    # fund type: JPY BTC MONA ETH XEM BCH
    # ask:sell, bid:buy
    # [0]:value [1]:quantity
    def getBTC_JPY(self):
        while (1):
            try:
                Btc_Jpy = self.zaif.depth('btc_jpy')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getBTC_JPY')
                time.sleep(1)
        askBtcJpy = Btc_Jpy['asks'][0][0]
        bidBtcJpy = Btc_Jpy['bids'][0][0]
        aveBtcJpy = (askBtcJpy + bidBtcJpy) / 2.0
        T_aveBtcJpy = Tick_int(int(aveBtcJpy), 5)
        return T_aveBtcJpy

    def getMONA_JPY(self):
        while (1):
            try:
                Mona_Jpy = self.zaif.depth('mona_jpy')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getMONA_JPY')
                time.sleep(1)
        askMonaJpy = Mona_Jpy['asks'][0][0]
        bidMonaJpy = Mona_Jpy['bids'][0][0]
        aveMonaJpy = (askMonaJpy + bidMonaJpy) / 2.0
        T_aveMonaJpy = Decimal(aveMonaJpy).quantize(Decimal('0.0'),
                                                    rounding=ROUND_DOWN)
        return T_aveMonaJpy

    def getMONA_BTC(self):
        while (1):
            try:
                Mona_Btc = self.zaif.depth('mona_btc')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getMONA_BTC')
                time.sleep(1)
        askMonaBtc = Mona_Btc['asks'][0][0]
        bidMonaBtc = Mona_Btc['bids'][0][0]
        aveMonaBtc = (askMonaBtc + bidMonaBtc) / 2.0
        T_aveMonaBtc = Decimal(aveMonaBtc).quantize(Decimal('0.00000000'),
                                                    rounding=ROUND_DOWN)
        return T_aveMonaBtc

    def getBCH_JPY(self):
        while (1):
            try:
                Bch_Jpy = self.zaif.depth('bch_jpy')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getBCH_JPY')
                time.sleep(1)
        askBchJpy = Bch_Jpy['asks'][0][0]
        bidBchJpy = Bch_Jpy['bids'][0][0]
        aveBchJpy = (askBchJpy + bidBchJpy) / 2.0
        T_aveBchJpy = Tick_int(int(aveBchJpy), 5)
        return T_aveBchJpy

    def getBCH_BTC(self):
        while (1):
            try:
                Bch_Btc = self.zaif.depth('bch_btc')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getBCH_BTC')
                time.sleep(1)
        askBchBtc = Bch_Btc['asks'][0][0]
        bidBchBtc = Bch_Btc['bids'][0][0]
        aveBchBtc = (askBchBtc + bidBchBtc) / 2.0
        T_aveBchBtc = Decimal(aveBchBtc).quantize(Decimal('0.0000'),
                                                  rounding=ROUND_DOWN)
        return T_aveBchBtc

    def getXEM_JPY(self):
        while (1):
            try:
                Xem_Jpy = self.zaif.depth('xem_jpy')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getXEM_JPY')
                time.sleep(1)
        askXemJpy = Xem_Jpy['asks'][0][0]
        bidXemJpy = Xem_Jpy['bids'][0][0]
        aveXemJpy = (askXemJpy + bidXemJpy) / 2.0
        T_aveXemJpy = Decimal(aveXemJpy).quantize(Decimal('0.0000'),
                                                  rounding=ROUND_DOWN)
        return T_aveXemJpy

    def getXEM_BTC(self):
        while (1):
            try:
                Xem_Btc = self.zaif.depth('xem_btc')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getXEM_BTC')
                time.sleep(1)
        askXemBtc = Xem_Btc['asks'][0][0]
        bidXemBtc = Xem_Btc['bids'][0][0]
        aveXemBtc = (askXemBtc + bidXemBtc) / 2.0
        T_aveXemBtc = Decimal(aveXemBtc).quantize(Decimal('0.00000000'),
                                                  rounding=ROUND_DOWN)
        return T_aveXemBtc

    def getETH_JPY(self):
        while (1):
            try:
                Eth_Jpy = self.zaif.depth('eth_jpy')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getETH_JPY')
                time.sleep(1)
        askEthJpy = Eth_Jpy['asks'][0][0]
        bidEthJpy = Eth_Jpy['bids'][0][0]
        aveEthJpy = (askEthJpy + bidEthJpy) / 2.0
        T_aveEthJpy = Tick_int(int(aveEthJpy), 5)
        return T_aveEthJpy

    def getETH_BTC(self):
        while (1):
            try:
                Eth_Btc = self.zaif.depth('eth_btc')
                break
            except:
                traceback.print_exc()
                self.createErrorLog('getETH_BTC')
                time.sleep(1)
        askEthBtc = Eth_Btc['asks'][0][0]
        bidEthBtc = Eth_Btc['bids'][0][0]
        aveEthBtc = (askEthBtc + bidEthBtc) / 2.0
        T_aveEthBtc = Decimal(aveEthBtc).quantize(Decimal('0.0000'),
                                                  rounding=ROUND_DOWN)
        return T_aveEthBtc

    # 三角裁定で利益が出るか計算
    def Monitoring(self):
        fj = self.getFunds()['jpy']

        if fj > self.investment:
            fj = self.investment

        self.getPublicAPI()
        aveBtcJpy = self.getBTC_JPY()
        aveMonaJpy = self.getMONA_JPY()
        aveMonaBtc = self.getMONA_BTC()
        aveBchJpy = self.getBCH_JPY()
        aveBchBtc = self.getBCH_BTC()
        aveXemJpy = self.getXEM_JPY()
        aveXemBtc = self.getXEM_BTC()
        aveEthJpy = self.getETH_JPY()
        aveEthBtc = self.getETH_BTC()

        # 買いと売りの中間点
        aves = [
            aveBtcJpy, aveMonaBtc, aveMonaJpy, aveBchBtc, aveBchJpy, aveXemBtc,
            aveXemJpy, aveEthBtc, aveEthJpy
        ]

        # ===========================================================
        # JPY->BTC, BTC->MONA, MONA->JPY
        #  BTC-ask,  MONA-ask,  MONA-bid

        # JPY->MONA, MONA->BTC, BTC->JPY
        #  MONA-ask,  MONA-bid,  BTC-bid

        # 手数料抜き============================================
        # Jpy_Btc_Mona = ((aveMonaJpy * fj) / (aveBtcJpy * aveMonaBtc))
        # Jpy_Mona_Btc = ((aveBtcJpy * aveMonaBtc * fj) / aveMonaJpy)
        # Jpy_Btc_Bch = ((aveBchJpy * fj) / (aveBtcJpy * aveBchBtc))
        # Jpy_Bch_Btc = ((aveBtcJpy * aveBchBtc * fj) / aveBchJpy)
        # Jpy_Btc_Xem = ((aveXemJpy * fj) / (aveBtcJpy * aveXemBtc))
        # Jpy_Xem_Btc = ((aveBtcJpy * aveXemBtc * fj) / aveXemJpy)
        # Jpy_Btc_Eth = ((aveEthJpy * fj) / (aveBtcJpy * aveEthBtc))
        # Jpy_Eth_Btc = ((aveBtcJpy * aveEthBtc * fj) / aveEthJpy)

        # 手数料あり============================================
        # ※decimal * floatができない.同じ型にキャストする必要あり
        Jpy_Btc_Mona = ((100 * float(aveMonaJpy))
                        / (float(aveMonaBtc) * (100 + self.fee_MONA_JPY))) * \
                       (100 / (float(aveBtcJpy) * (100 + self.fee_MONA_BTC))) * \
                       ((100 * fj) / (100 + self.fee_BTC_JPY))
        Jpy_Mona_Btc = ((100 * float(aveBtcJpy) * float(aveMonaBtc))
                        / (100 + self.fee_BTC_JPY)) * \
                       (100 / (float(aveMonaJpy) * (100 + self.fee_MONA_BTC))) * \
                       ((100 * fj) / (100 + self.fee_MONA_JPY))

        Jpy_Btc_Bch = ((100 * float(aveBchJpy))
                       / (float(aveBchBtc) * (100 + self.fee_BCH_JPY))) * \
                      (100 / (float(aveBtcJpy) * (100 + self.fee_BCH_BTC))) * \
                      ((100 * fj) / (100 + self.fee_BTC_JPY))
        Jpy_Bch_Btc = ((100 * float(aveBtcJpy) * float(aveBchBtc))
                       / (100 + self.fee_BTC_JPY)) * \
                      (100 / (float(aveBchJpy) * (100 + self.fee_BCH_BTC))) * \
                      ((100 * fj) / (100 + self.fee_BCH_JPY))

        Jpy_Btc_Xem = ((100 * float(aveXemJpy))
                       / (float(aveXemBtc) * (100 + self.fee_XEM_JPY))) * \
                      (100 / (float(aveBtcJpy) * (100 + self.fee_XEM_BTC))) * \
                      ((100 * fj) / (100 + self.fee_BTC_JPY))
        Jpy_Xem_Btc = ((100 * float(aveBtcJpy) * float(aveXemBtc))
                       / (100 + self.fee_BTC_JPY)) * \
                      (100 / (float(aveXemJpy) * (100 + self.fee_XEM_BTC))) * \
                      ((100 * fj) / (100 + self.fee_XEM_JPY))

        Jpy_Btc_Eth = ((100 * float(aveEthJpy))
                       / (float(aveEthBtc) * (100 + self.fee_ETH_JPY))) * \
                      (100 / (float(aveBtcJpy) * (100 + self.fee_ETH_BTC))) * \
                      ((100 * fj) / (100 + self.fee_BTC_JPY))
        Jpy_Eth_Btc = ((100 * float(aveBtcJpy) * float(aveEthBtc))
                       / (100 + self.fee_BTC_JPY)) * \
                      (100 / (float(aveEthJpy) * (100 + self.fee_ETH_BTC))) * \
                      ((100 * fj) / (100 + self.fee_ETH_JPY))

        # 各予想結果額
        estimates = [
            Jpy_Btc_Mona, Jpy_Mona_Btc, Jpy_Btc_Bch, Jpy_Bch_Btc, Jpy_Btc_Xem,
            Jpy_Xem_Btc, Jpy_Btc_Eth, Jpy_Eth_Btc
        ]

        # 最も高い予想結果額
        maxIndex = numpy.argmax(estimates)

        if maxIndex == 0 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_mona):
            judge = 'Jpy_Btc_Mona'
        elif maxIndex == 1 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_mona):
            judge = 'Jpy_Mona_Btc'
        elif maxIndex == 2 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_bch):
            judge = 'Jpy_Btc_Bch'
        elif maxIndex == 3 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_bch):
            judge = 'Jpy_Bch_Btc'
        elif maxIndex == 4 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_xem):
            judge = 'Jpy_Btc_Xem'
        elif maxIndex == 5 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_xem):
            judge = 'Jpy_Xem_Btc'
        elif maxIndex == 6 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_eth):
            judge = 'Jpy_Btc_Eth'
        elif maxIndex == 7 \
                and estimates[maxIndex] > (fj + self.threshold_jpy_btc_eth):
            judge = 'Jpy_Eth_Btc'
        else:
            judge = 'no routes'

        # 各予想利益額
        diffs = [
            int(Jpy_Btc_Mona - fj),
            int(Jpy_Mona_Btc - fj),
            int(Jpy_Btc_Bch - fj),
            int(Jpy_Bch_Btc - fj),
            int(Jpy_Btc_Xem - fj),
            int(Jpy_Xem_Btc - fj),
            int(Jpy_Btc_Eth - fj),
            int(Jpy_Eth_Btc - fj)
        ]

        resultList = [judge, fj, diffs[maxIndex], diffs, aves]
        return resultList

    # コメント'AutoTA'の注文が残っているか確認
    def checkActiveOrders(self, pair: str):
        # active_ordersの形式:
        # {'270906448': {
        # 'currency_pair': 'mona_btc',
        # 'action': 'ask',
        # 'amount': 33.0,
        # 'price': 0.00035692,
        # 'timestamp': '1510122394',
        # 'comment': ''}}
        time.sleep(0.3)
        self.getPrivateAPI()
        orderID = 0  # 注文が無ければこのまま0を返す
        price = 0
        amount = 0
        orders = []
        while 1:
            try:
                if pair == 'btc_jpy':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='btc_jpy'))
                elif pair == 'mona_btc':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='mona_btc'))
                elif pair == 'mona_jpy':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='mona_jpy'))
                elif pair == 'xem_btc':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='xem_btc'))
                elif pair == 'xem_jpy':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='xem_jpy'))
                elif pair == 'bch_btc':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='bch_btc'))
                elif pair == 'bch_jpy':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='bch_jpy'))
                elif pair == 'eth_btc':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='eth_btc'))
                elif pair == 'eth_jpy':
                    orders.append(
                        self.zaifp.active_orders(currency_pair='eth_jpy'))
                else:
                    pass
                break
            except:
                traceback.print_exc()
                time.sleep(1)

        # コメントが'AutoTA'のオーダーがあればID,価格,数量を返す
        for i in range(len(orders)):
            if orders[i] != []:
                for j in orders[i].keys():
                    if re.search(self.order_comment,
                                 str(orders[i][j]['comment'])):
                        orderID = int(j)
                        price = orders[i][j]['price']
                        amount = orders[i][j]['amount']
        resultList = [orderID, price, amount]
        return resultList

    # 注文IDと通貨ペアを指定して注文を取り消し
    def cancelOrder(self, orderID: int, pair: str):
        cancelFlag = False
        time.sleep(1)
        try:
            self.zaifp.cancel_order(order_id=orderID, currency_pair=pair)
            print('order canceled')
            cancelFlag = True
        except:
            traceback.print_exc()
            self.createErrorLog('cancelOrder')
        time.sleep(1)
        return cancelFlag

    # コメント'AutoTA'を付けて注文実行
    def tradePairs(self, pair, act, price, amount):
        while 1:
            try:
                self.getPrivateAPI()
                self.zaifp.trade(currency_pair=pair,
                                 action=act,
                                 price=price,
                                 amount=amount,
                                 comment=self.order_comment)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('tradePairs')
            time.sleep(1)

    # 各取引======================================
    # JPY->BTC->MONA
    def order_JPY_BTC(self, prevFund, T_aveBtcJpy):
        print('JPY->BTC: ', end='', flush=True)
        # 手数料分を残して取引
        tradeJPY = (100 * prevFund) / (100 + self.fee_BTC_JPY)
        pair = 'btc_jpy'  # trade pair
        act = 'bid'  # ask ( sell order ) or bid ( buy order )
        price = T_aveBtcJpy
        amount = Decimal(tradeJPY / float(price)).quantize(Decimal('0.0000'),
                                                           rounding=ROUND_DOWN)
        print(price, end=' amount: ', flush=True)
        print(amount)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_BTC_MONA(self, T_aveMonaBtc):
        print('BTC->MONA: ', end='', flush=True)
        while 1:
            try:
                myBTC = self.getFunds()['btc']
                # 手数料分を残して取引
                tradeBTC = (100 * myBTC) / (100 + self.fee_MONA_BTC)
                pair = 'mona_btc'  # trade pair
                act = 'bid'  # ask ( sell order ) or bid ( buy order )
                price = T_aveMonaBtc
                amount = Decimal(tradeBTC / float(price)).quantize(
                    Decimal('0'), rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('order_BTC_MONA')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_MONA_JPY(self, T_aveMonaJpy):
        print('MONA->JPY: ', end='', flush=True)
        while 1:
            try:
                myMONA = self.getFunds()['mona']
                # 手数料分を残して取引
                tradeMONA = (100 * myMONA) / (100 + self.fee_MONA_JPY)
                pair = 'mona_jpy'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveMonaJpy
                amount = int(tradeMONA)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('order_MONA_JPY')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
        return price * amount

    # JPY->MONA->BTC
    def order_JPY_MONA(self, prevFund, T_aveMonaJpy):
        print('JPY->MONA: ', end='', flush=True)
        while 1:
            try:
                # 手数料分を残して取引
                tradeJPY = (100 * prevFund) / (100 + self.fee_MONA_JPY)
                pair = 'mona_jpy'  # trade pair
                act = 'bid'  # ask ( sell order ) or bid ( buy order )
                price = T_aveMonaJpy
                amount = Decimal(tradeJPY / float(price)).quantize(
                    Decimal('0'), rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('JPY->MONA')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_MONA_BTC(self, T_aveMonaBtc):
        print('MONA->BTC: ', end='', flush=True)
        while 1:
            try:
                myMONA = self.getFunds()['mona']
                # 手数料分を残して取引
                tradeMONA = (100 * myMONA) / (100 + self.fee_MONA_BTC)
                pair = 'mona_btc'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveMonaBtc
                amount = int(tradeMONA)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('MONA->BTC')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_BTC_JPY(self, T_aveBtcJpy):
        print('BTC->JPY: ', end='', flush=True)
        while 1:
            try:
                myBTC = self.getFunds()['btc']
                # 手数料分を残して取引
                tradeBTC = (100 * myBTC) / (100 + self.fee_BTC_JPY)
                pair = 'btc_jpy'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveBtcJpy
                amount = Decimal(tradeBTC).quantize(Decimal('0.0000'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BTC->JPY')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
        return price * amount

    # JPY->BTC->BCH
    def order_BTC_BCH(self, T_aveBchBtc):
        print('BTC->BCH: ', end='', flush=True)
        while 1:
            try:
                myBTC = self.getFunds()['btc']
                # 手数料分を残して取引
                tradeBTC = (100 * myBTC) / (100 + self.fee_BCH_BTC)
                pair = 'bch_btc'  # trade pair
                act = 'bid'  # ask ( sell order ) or bid ( buy order )
                price = T_aveBchBtc
                amount = Decimal(tradeBTC / float(price)).quantize(
                    Decimal('0.0000'), rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BTC->BCH')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_BCH_JPY(self, T_aveBchJpy):
        print('BCH->JPY: ', end='', flush=True)
        while 1:
            try:
                myBCH = self.getFunds()['BCH']
                # 手数料分を残して取引
                tradeBCH = (100 * myBCH) / (100 + self.fee_BCH_JPY)
                pair = 'bch_jpy'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveBchJpy
                amount = Decimal(tradeBCH).quantize(Decimal('0.0000'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BCH->JPY')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
        return price * amount

    # JPY->BCH->BTC
    def order_JPY_BCH(self, prevFund, T_aveBchJpy):
        print('JPY->BCH: ', end='', flush=True)
        # 手数料分を残して取引
        tradeJPY = (100 * prevFund) / (100 + self.fee_BCH_JPY)
        pair = 'bch_jpy'  # trade pair
        act = 'bid'  # ask ( sell order ) or bid ( buy order )
        price = T_aveBchJpy
        amount = Decimal(tradeJPY / float(price)).quantize(Decimal('0.0000'),
                                                           rounding=ROUND_DOWN)
        print(price, end=' amount: ', flush=True)
        print(amount)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_BCH_BTC(self, T_aveBchBtc):
        print('BCH->BTC: ', end='', flush=True)
        while 1:
            try:
                myBCH = self.getFunds()['BCH']
                # 手数料分を残して取引
                tradeBCH = (100 * myBCH) / (100 + self.fee_BCH_BTC)
                pair = 'bch_btc'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveBchBtc
                amount = Decimal(tradeBCH).quantize(Decimal('0.0000'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BCH->BTC')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    # JPY->BTC->XEM
    def order_BTC_XEM(self, T_aveXemBtc):
        print('BTC->XEM: ', end='', flush=True)
        while 1:
            try:
                myBTC = self.getFunds()['btc']
                # 手数料分を残して取引
                tradeBTC = (100 * myBTC) / (100 + self.fee_XEM_BTC)
                pair = 'xem_btc'  # trade pair
                act = 'bid'  # ask ( sell order ) or bid ( buy order )
                price = T_aveXemBtc
                amount = Decimal(tradeBTC / float(price)).quantize(
                    Decimal('0'), rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BTC->XEM')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_XEM_JPY(self, T_aveXemJpy):
        print('XEM->JPY: ', end='', flush=True)
        while 1:
            try:
                myXEM = self.getFunds()['xem']
                # 手数料分を残して取引
                tradeXEM = (100 * myXEM) / (100 + self.fee_XEM_JPY)
                pair = 'xem_jpy'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveXemJpy
                amount = Decimal(tradeXEM).quantize(Decimal('0.0'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('XEM->JPY')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
        return price * amount

    # JPY->XEM->BTC
    def order_JPY_XEM(self, prevFund, T_aveXemJpy):
        print('JPY->XEM: ', end='', flush=True)
        # 手数料分を残して取引
        tradeJPY = (100 * prevFund) / (100 + self.fee_XEM_JPY)
        pair = 'xem_jpy'  # trade pair
        act = 'bid'  # ask ( sell order ) or bid ( buy order )
        price = T_aveXemJpy
        amount = Decimal(tradeJPY / float(price)).quantize(Decimal('0.0'),
                                                           rounding=ROUND_DOWN)
        print(price, end=' amount: ', flush=True)
        print(amount)
        if amount >= 0.1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_XEM_BTC(self, T_aveXemBtc):
        print('XEM->BTC: ', end='', flush=True)
        while 1:
            try:
                myXEM = self.getFunds()['xem']
                # 手数料分を残して取引
                tradeXEM = (100 * myXEM) / (100 + self.fee_XEM_BTC)
                pair = 'xem_btc'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveXemBtc
                amount = Decimal(tradeXEM).quantize(Decimal('0'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('XEM->BTC')
            time.sleep(1)
        time.sleep(1)
        if amount >= 1:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    # JPY->BTC->ETH
    def order_BTC_ETH(self, T_aveEthBtc):
        print('BTC->ETH: ', end='', flush=True)
        while 1:
            try:
                myBTC = self.getFunds()['btc']
                # 手数料分を残して取引
                tradeBTC = (100 * myBTC) / (100 + self.fee_ETH_BTC)
                pair = 'eth_btc'  # trade pair
                act = 'bid'  # ask ( sell order ) or bid ( buy order )
                price = T_aveEthBtc
                amount = Decimal(tradeBTC / float(price)).quantize(
                    Decimal('0.0000'), rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('BTC->ETH')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_ETH_JPY(self, T_aveEthJpy):
        print('ETH->JPY: ', end='', flush=True)
        while 1:
            try:
                myETH = self.getFunds()['ETH']
                # 手数料分を残して取引
                tradeETH = (100 * myETH) / (100 + self.fee_ETH_JPY)
                pair = 'eth_jpy'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveEthJpy
                amount = Decimal(tradeETH).quantize(Decimal('0.0000'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('ETH->JPY')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
        return price * amount

    # JPY->ETH->BTC
    def order_JPY_ETH(self, prevFund, T_aveEthJpy):
        print('JPY->ETH: ', end='', flush=True)
        # 手数料分を残して取引
        tradeJPY = (100 * prevFund) / (100 + self.fee_ETH_JPY)
        pair = 'eth_jpy'  # trade pair
        act = 'bid'  # ask ( sell order ) or bid ( buy order )
        price = T_aveEthJpy
        amount = Decimal(tradeJPY / float(price)).quantize(Decimal('0.0000'),
                                                           rounding=ROUND_DOWN)
        print(price, end=' amount: ', flush=True)
        print(amount)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')

    def order_ETH_BTC(self, T_aveEthBtc):
        print('ETH->BTC: ', end='', flush=True)
        while 1:
            try:
                myETH = self.getFunds()['ETH']
                # 手数料分を残して取引
                tradeETH = (100 * myETH) / (100 + self.fee_ETH_BTC)
                pair = 'eth_btc'  # trade pair
                act = 'ask'  # ask ( sell order ) or bid ( buy order )
                price = T_aveEthBtc
                amount = Decimal(tradeETH).quantize(Decimal('0.0000'),
                                                    rounding=ROUND_DOWN)
                print(price, end=' amount: ', flush=True)
                print(amount)
                break
            except:
                traceback.print_exc()
                self.createErrorLog('ETH->BTC')
            time.sleep(1)
        time.sleep(1)
        if amount >= 0.0001:
            self.tradePairs(pair, act, price, amount)
        else:
            print('Do not Trade. Checking active orders...')
コード例 #9
0
plt.plot(predictions, color='blue', label='percentage')
plt.plot(y_real_test, color='green', label='Real Price')
plt.title('Cripto currency prediction')
plt.xlabel('Time')
plt.ylabel('green:Real Price blue: prediction(%) red: teacher(%)')
plt.legend()
plt.show()

print("FINAL money")
print(trade.simulate_trade(y_real_test, X_test, model))
'''
ZaifTrade
'''

from zaifapi import ZaifPublicApi
public_zaif = ZaifPublicApi()
import time
#添え字は0に近い方が強い。競っている
#入札をキャンセルする関数を作る。
# float(public_zaif.depth('btc_jpy')['asks'][0][0])#売
# float(public_zaif.depth('btc_jpy')['bids'][0][0])#買
print(public_zaif.depth('btc_jpy')['bids'][0][0])
from zaifapi import *
public_zaif = ZaifPublicApi()

trade_zaif = ZaifTradeApi('', '')

history = []
sleep_time = 0.2
#askは売 bidは買
for num in range(3000):
コード例 #10
0
def main():
    zaif_public = ZaifPublicApi()
    zaif_trade = ZaifTradeApi(KEY, SECRET)
    last_price = 0
    open_orders = 0
#    position_status = OPEN
    position_status = BOUGHT
    buy_count = 0
    sell_count = 0
    macd_trend = ACCEND
    buy_order_price = 0

    while True:
        start_time = time.time()
        order_status = EXCEPTION
        try:
            macd = MACD(currency_pair='btc_jpy', period='1h', short=10, long=21, signal=9)
            response = macd.request_data(count=1)
            action_signal = response[0]['macdhist']
            '''
            macd = MACD(currency_pair='btc_jpy', period='1m', short=10, long=21, signal=9)
            response = macd.request_data(count=4)
            a = response[1]['macd']-response[0]['macd']+MACD_THREHOLD
            b = response[2]['macd']-response[1]['macd']+MACD_THREHOLD
            
            if a < 0 and b < 0: macd_trend = DECEND
            else: macd_trend = ACCEND
            '''
            account_info = zaif_trade.get_info2()
            funds_jpy = account_info['funds']['jpy']
            funds_btc = account_info['funds']['btc']
            open_orders = account_info['open_orders']
            
            last_price = zaif_public.last_price('btc_jpy')['last_price']

        except Exception as ex:
            print(f"[info_exception]{ex}")
            time.sleep(0.2)
            continue

        if open_orders == 0 and position_status == OPEN and action_signal > SIGNAL_THREHOLD:
            print('[info]buy_btc...')
            ask_amount = float(int((funds_jpy/last_price)*10000.0)/10000.0)
            while order_status == EXCEPTION:
                try:
                    buy_order_price = int(last_price)
                    trade_result = zaif_trade.trade(currency_pair="btc_jpy",action="bid",price=buy_order_price,amount=ask_amount)
                    buy_count += 1
                    order_status = NORMAL
                    position_status = BOUGHT
                    print(f"[buy_ok]#{buy_count},signal:{action_signal:.2f},buy_price:{buy_order_price},amount:{ask_amount},time:{datetime.datetime.today()}")
                    break
                    
                except Exception as ex:
                    print(f"[buy_exception]{ex}")
                    order_status = EXCEPTION
                    time.sleep(0.15)
          
        elif open_orders == 0 and position_status == BOUGHT and action_signal < (-1.0*SIGNAL_THREHOLD):
            print('[info]sell_btc...')
            bid_amount = float(int(funds_btc*10000.0)/10000.0)
            if bid_amount > 0.01 and last_price > (buy_order_price-LOSSCUT):
                while order_status == EXCEPTION:
                    try:
                        trade_result = zaif_trade.trade(currency_pair="btc_jpy",action="ask",price=int(last_price),amount=bid_amount)
                        sell_count += 1
                        order_status = NORMAL
                        position_status = OPEN
                        print(f"[sell_ok]#{sell_count},signal:{action_signal:.2f},sell_price:{last_price},amount:{bid_amount},time:{datetime.datetime.today()}")
                        break
                        
                    except Exception as ex:
                        print(f"[sell_exception]{ex}")
                        order_status = EXCEPTION
                        time.sleep(0.15)
            else:
                position_status = OPEN
                print(f"[info]position_status:OPEN")
        '''
        elif open_orders == 0 and position_status == BOUGHT and macd_trend == DECEND:
            bid_amount = float(int(funds_btc*10000.0)/10000.0)
            if bid_amount > 0.01 and last_price > (buy_order_price-LOSSCUT):
                print('[info]sell_btc as 1m macd decent...')
                while order_status == EXCEPTION:
                    try:
                        trade_result = zaif_trade.trade(currency_pair="btc_jpy",action="ask",price=int(last_price),amount=bid_amount)
                        sell_count += 1
                        order_status = NORMAL
                        position_status = BOUGHT
                        print(f"[sell_ok]#{sell_count},signal:{action_signal:.2f},sell_price:{last_price},amount:{bid_amount},time:{datetime.datetime.today()}")
                        break
                        
                    except Exception as ex:
                        print(f"[sell_exception]{ex}")
                        order_status = EXCEPTION
                        time.sleep(0.15)
        '''
        elpsed_time = time.time()-start_time
        if (SLEEP_TIME-elpsed_time) > 0:
            time.sleep(SLEEP_TIME-elpsed_time)
コード例 #11
0
def writingData():
    
    global elpsed_time,last_trade_price
    #取引時間の書き込み
    time_f = open("tradingTime",'a')
    time_f.write(str(elpsed_time)+"\n")
    time_f.close()
    
    last_price_f = open("tradingPrice",'a')
    last_price_f.write(str(last_trade_price)+"\n")
    last_price_f.close()


if __name__=='__main__':
    # get environ ver
    zaif_public = ZaifPublicApi()
    zaif_trade = ZaifTradeApi(KEY,SECRET)
    
    CANCEL_FLUG = False
    
    last_trade_price = int(zaif_public.last_price('btc_jpy')["last_price"])
    
    
    while(True):
        start_time = time.time()
        print("■ 現在の情報です")
        try:
            funds_btc = zaif_trade.get_info2()['funds']['btc']
            funds_jpy = zaif_trade.get_info2()['funds']['jpy']
            last_price = int(zaif_public.last_price('btc_jpy')["last_price"])
            
コード例 #12
0
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

# 追加
import os

import pybitflyer  #bitFlyerのAPI取得

bitflyer = pybitflyer.API()
bit_ticker = bitflyer.ticker(product_code="BTC_JPY")

from zaifapi import ZaifPublicApi  #ZaifのAPI取得

zaif = ZaifPublicApi()
zaif_ticker = zaif.ticker('btc_jpy')

app = Flask(__name__)

# 以下2行追加
YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
コード例 #13
0
ファイル: exporter.py プロジェクト: tetocode/zaifexport
class Exporter:
    ORDER_MAP = dict(bid='買', ask='売', both='自己')
    FUTURE_MAP = {
        1: 'AirFX',
        2: '四半期6月(07-01) ',
        3: '四半期9月(10-01)',
        4: '四半期12月(01-01)',
        5: '四半期3月(04-01)',
    }

    def __init__(self, api_key: str, api_secret: str,
                 wait_interval: float,
                 limit: int,
                 cache_limit: int,
                 currencies: Optional[List[str]]):
        self.public_api = ZaifPublicApi()
        self.trade_api = ZaifTradeApi(api_key, api_secret)
        self.futures_public_api = ZaifFuturesPublicApi()
        self.futures_trade_api = ZaifLeverageTradeApi(api_key, api_secret)
        self._wait_interval = wait_interval
        self._limit = limit
        self._cache_limit = cache_limit
        if currencies:
            currencies = [x.upper() for x in currencies]
        self._currencies = currencies

    def get_history(self, fn: Callable[[dict], dict], parse_fn: Callable[[dict], Iterator[dict]],
                    **kwargs) -> Generator[dict, None, None]:
        def retry_wrapper(*_args, **_kwargs):
            while True:
                try:
                    print('.', file=sys.stderr, end='', flush=True)
                    return fn(*_args, **_kwargs)
                except ZaifApiError as e:
                    s = str(e)
                    if 'time wait restriction, please try later.' in s:
                        print('rate limit exceeded. wait and retry...', file=sys.stderr)
                        time.sleep(self._wait_interval)
                    elif 'return status code is 502' in s:
                        print('502 error. wait and retry...', file=sys.stderr)
                        time.sleep(self._wait_interval)
                    elif 'return status code is 504' in s:
                        print('504 error. wait and retry...', file=sys.stderr)
                        time.sleep(self._wait_interval)
                    else:
                        raise

        from_i = 0
        params = kwargs.copy()
        params.update(count=self._limit)
        cache = OrderedDict()
        cache_limit = self._cache_limit
        while True:
            params['from_num'] = from_i
            res = retry_wrapper(**params)
            if not len(res):
                break
            for k, v in sorted(res.items(), key=lambda _x: int(_x[0]), reverse=True):
                k = int(k)
                v['id'] = k
                # ID降順で取得できる保証がないので、
                # IDをキャッシュしてキャッシュに無いもののみ出力する。
                if k not in cache:
                    cache[k] = True
                    if len(cache) > cache_limit:
                        cache.popitem(last=False)
                    for x in parse_fn(v):
                        yield x
            from_i += len(res)

    @classmethod
    def convert_timestamp(cls, timestamp: Union[int, float], tz: pytz.timezone = JST) -> str:
        timestamp = float(timestamp)
        return pytz.UTC.localize(datetime.utcfromtimestamp(timestamp)).astimezone(tz).isoformat()

    @classmethod
    def write_csv(cls, gen: Generator[dict, None, None], file):
        writer = None
        for data in gen:
            if not writer:
                writer = csv.DictWriter(file, fieldnames=tuple(data.keys()))
                writer.writeheader()
            writer.writerow(data)

    def export_spot(self) -> Generator[dict, None, None]:
        pairs = self.public_api.currency_pairs('all')
        for pair in sorted(pairs, key=lambda x: x['name']):
            def parse(trade: dict) -> Iterator[dict]:
                """
                "182": {
                    "currency_pair": "btc_jpy",
                    "action": "bid",
                    "amount": 0.03,
                    "price": 56000,
                    "fee": 0,
                    "your_action": "ask",
                    "bonus": 1.6,
                    "timestamp": 1402018713,
                    "comment" : "demo"
                }
                """
                x = OrderedDict()
                is_taker = trade['action'] == trade['your_action']
                x['分類'] = '現物'
                x['ID'] = trade['id']
                x['日時'] = self.convert_timestamp(trade['timestamp'])
                x['通貨ペア'] = '/'.join(trade['currency_pair'].upper().split('_'))
                x['注文種別'] = self.ORDER_MAP[trade['your_action']]
                x['TAKER/MAKER'] = 'TAKER' if is_taker else 'MAKER'
                x['価格'] = trade['price']
                x['数量'] = trade['amount']
                x['手数料'] = trade['fee_amount']
                x['ボーナス'] = trade['bonus']
                x['コメント'] = trade['comment']

                results = []
                if trade['your_action'] == 'both':
                    if trade['action'] == 'bid':
                        # 買い
                        x['注文種別'] = '自己買'
                        x['TAKER/MAKER'] = 'TAKER'
                        results.append(x.copy())
                        x['注文種別'] = '自己売'
                        x['TAKER/MAKER'] = 'MAKER'
                        results.append(x.copy())
                    elif trade['action'] == 'ask':
                        # 売り
                        x['注文種別'] = '自己売'
                        x['TAKER/MAKER'] = 'TAKER'
                        results.append(x.copy())
                        x['注文種別'] = '自己買'
                        x['TAKER/MAKER'] = 'MAKER'
                        results.append(x.copy())
                    else:
                        assert False, 'unknown action: {}'.format(trade)
                else:
                    results.append(x)
                return results

            currency_pair = pair['currency_pair']
            yield from self.get_history(self.trade_api.trade_history, parse, currency_pair=currency_pair)

    def _export_margin_or_future(self, **kwargs) -> Generator[dict, None, None]:
        def parse(trade: dict) -> Iterator[dict]:
            """
            "182": {
                "group_id": 1,
                "currency_pair": "btc_jpy",
                "action": "bid",
                "leverage": 2.5,
                "price": 110005,
                "limit": 130000,
                "stop": 90000,
                "amount": 0.03,
                "fee_spent": 0,
                "timestamp": 1402018713,
                "term_end": 1404610713,
                "timestamp_closed": 1402019000,
                "deposit": 35.76 ,
                "deposit_jpy": 35.76,
                "refunded": 35.76 ,
                "refunded_jpy": 35.76,
                "swap": 0,
            }
            group_id	グループID	int
            currency_pair	通貨ペア	str
            action	bid(買い) or ask(売り)	str
            amount	数量	float
            price	価格	float
            limit	リミット価格	float
            stop	ストップ価格	float
            timestamp	発注日時	UNIX_TIMESTAMP
            term_end	注文の有効期限	UNIX_TIMESTAMP
            leverage	レバレッジ	float
            fee_spent	支払い手数料	float
            timestamp_closed	クローズ日時	UNIX_TIMESTAMP
            price_avg	建玉平均価格	float
            amount_done	建玉数	float
            close_avg	決済平均価格	float
            close_done	決済数	float
            deposit_xxx	実際にデポジットした額(xxxは通貨コード)	float
            deposit_price_xxx	デポジット時計算レート(xxxは通貨コード)	float
            refunded_xxx	実際に返却した額(xxxは通貨コード)	float
            refunded_price_xxx	実際に返却した額(xxxは通貨コード)	float
            swap	受け取ったスワップの額(AirFXのみ)	float
            guard_fee	追証ガード手数料(信用取引のみ)	float
            """
            x = OrderedDict()
            is_executed = 'amount_done' in trade
            if 'group_id' in trade:
                x['分類'] = '先物'
                x['先物グループ'] = self.FUTURE_MAP[trade['group_id']]
            else:
                x['分類'] = '信用'
            x['ID'] = trade['id']
            x['発注日時'] = self.convert_timestamp(trade['timestamp'])
            x['決済日時'] = self.convert_timestamp(trade['timestamp_closed'])
            x['通貨ペア'] = '/'.join(trade['currency_pair'].upper().split('_'))
            if is_executed:
                x['ステータス'] = '成立'
            else:
                x['ステータス'] = '取消済み(建玉不成立)'
            x['注文種別'] = self.ORDER_MAP[trade['action']]
            x['数量'] = trade['amount']
            x['価格'] = trade['price']
            x['リミット価格'] = trade.get('limit')
            x['ストップ価格'] = trade.get('stop')
            x['支払い手数料'] = trade['fee_spent']
            x['建玉平均価格'] = trade.get('price_avg')
            x['建玉数'] = trade.get('amount_done')
            x['決済平均価格'] = trade.get('close_avg')
            x['決済数'] = trade.get('close_done')
            x['スワップ'] = trade.get('swap')
            swap = trade.get('swap', 0)
            x['追証ガード手数料(信用取引のみ)'] = trade.get('guard_fee')
            guard_fee = trade.get('guard_fee', 0)
            if is_executed:
                pnl = trade['close_avg'] * trade['close_done'] - trade['price_avg'] * trade['amount_done']
                pnl = pnl if trade['action'] == 'bid' else -pnl
                pnl_with_fee_swap = pnl + swap - guard_fee - trade['fee_spent']
            else:
                pnl = None
                pnl_with_fee_swap = None
            x['ポジション損益'] = pnl
            x['ポジション損益(手数料・スワップ込み)'] = pnl_with_fee_swap
            return [x]

        yield from self.get_history(self.futures_trade_api.get_positions, parse, **kwargs)

    def export_margin(self) -> Generator[dict, None, None]:
        yield from self._export_margin_or_future(type='margin')

    def export_future(self) -> Generator[dict, None, None]:
        groups = self.futures_public_api.groups('all')
        for group_id in sorted(map(lambda x: x['id'], groups)):
            yield from self._export_margin_or_future(type='futures', group_id=group_id)

    def export_deposit(self) -> Generator[dict, None, None]:
        currencies = [x['name'] for x in self.public_api.currencies('all')]
        for currency in sorted(currencies):
            if self._currencies and (currency.upper() not in self._currencies):
                continue

            def parse(d: dict) -> Iterator[dict]:
                """
                "3816":{
                    "timestamp":1435745065,
                    "address":"12qwQ3sPJJAosodSUhSpMds4WfUPBeFEM2",
                    "amount":0.001,
                    "txid":"64dcf59523379ba282ae8cd61d2e9382c7849afe3a3802c0abb08a60067a159f",
                },
                """
                return [OrderedDict([
                    ('通貨', currency),
                    ('ID', d['id']),
                    ('日時', self.convert_timestamp(d['timestamp'])),
                    ('数量', d['amount']),
                    ('入金アドレス', d.get('address')),
                    ('トランザクション', d.get('txid')),
                ])]

            yield from self.get_history(self.trade_api.deposit_history, parse, currency=currency)

    def export_withdrawal(self) -> Generator[dict, None, None]:
        currencies = [x['name'] for x in self.public_api.currencies('all')]
        for currency in sorted(currencies):
            if self._currencies and (currency.upper() not in self._currencies):
                continue

            def parse(d: dict) -> Iterator[dict]:
                """
                "3816":{
                    "timestamp":1435745065,
                    "address":"12qwQ3sPJJAosodSUhSpMds4WfUPBeFEM2",
                    "amount":0.001,
                    "txid":"64dcf59523379ba282ae8cd61d2e9382c7849afe3a3802c0abb08a60067a159f",
                },
                """
                bank_processed_at = d.get('processed')
                if bank_processed_at:
                    bank_processed_at = self.convert_timestamp(bank_processed_at)
                return [OrderedDict([
                    ('通貨', currency),
                    ('ID', d['id']),
                    ('日時', self.convert_timestamp(d['timestamp'])),
                    ('数量', d['amount']),
                    ('手数料', d['fee']),
                    ('出金アドレス', d.get('address')),
                    ('トランザクション', d.get('txid')),
                    ('銀行名', d.get('bank_name')),
                    ('支店名', d.get('bank_branch')),
                    ('口座種別', d.get('account_type')),
                    ('口座番号', d.get('account_no')),
                    ('口座名義', d.get('account_kana')),
                    ('処理日時', bank_processed_at),
                ])]

            yield from self.get_history(self.trade_api.withdraw_history, parse, currency=currency)
コード例 #14
0
#!/usr/bin/env python

from zaifapi import ZaifPublicApi
from pprint import pprint
from decimal import *
import datetime
import locale
import configparser
import os
import time

config = configparser.SafeConfigParser()
config.read('./config.ini', 'UTF-8')
zaif = ZaifPublicApi()

false = False
debug = False

money = 10000
count = 0

#os.system('clear')
os.system('cls')

cpairs_btc_jpy = [{
    "description":
    "\u30d3\u30c3\u30c8\u30b3\u30a4\u30f3\u30fb\u65e5\u672c\u5186\u306e\u53d6\u5f15\u3092\u884c\u3046\u3053\u3068\u304c\u3067\u304d\u307e\u3059",
    "id": 1,
    "aux_unit_point": 0,
    "item_japanese": "\u30d3\u30c3\u30c8\u30b3\u30a4\u30f3",
    "name": "BTC/JPY",
コード例 #15
0
ファイル: helpers.py プロジェクト: xzeus44/zaif-bot
def get_btc_last_price():
    zaif = ZaifPublicApi()
    last_price = zaif.last_price('btc_jpy')
    return int(last_price['last_price'])