<jupyter_start><jupyter_text>データ取得<jupyter_code># bitflyerからティッカーを取得
import requests
response = requests.get("https://api.bitflyer.jp/v1/ticker/")
# json形式に変換
data = response.json()
print(data)
print(data['best_bid'])
# 期間を指定してcryptowatchからデータを取得
response = requests.get('https://api.cryptowat.ch/markets/bitflyer/btcjpy/ohlc?periods=86400&after=1514764800')
response
min_ = 10**9
for num, val in enumerate(response['result']['86400']):
    # print(num, val, val[3])
    min_ = min(min_, val[3])
print(min_)<jupyter_output>354350<jupyter_text>指値注文<jupyter_code># api経由で指し値注文を入れる
# ccxtを使えば簡単だが、勉強用に書いたコード
import hashlib
import hmac
import requests
import datetime
import json

api_key = ''
api_secret = ''

base_url = 'https://api.bitflyer.jp'
path_url = '/v1/me/sendchildorder'
method = 'POST'

timestamp = str(datetime.datetime.today())

param = {
	"product_code" : "FX_BTC_JPY",
	"child_order_type" : "LIMIT",
	"side" : "BUY",
	"price" : 指値,
	"size" : 0.01,
}
body = json.dumps(params)

message = timestamp + method + path_url + body
signature = hmac.new(bytearray(api_secret.encode('utf-8')), message.encode('utf-8'), digestmod = hashlib.sha256).hexdigest()

headers = {
	'ACCESS-KEY' : api_key,
	'ACCESS-TIMESTAMP' : timestamp,
	'ACCESS-SIGN' : signature,
	'Content-Type' : 'application/json'
}

response = requests.post(base_url + path_url, data=body, headers = headers )
print(response.status_code)
print(response.json())<jupyter_output><empty_output><jupyter_text>ティッカー情報取得<jupyter_code># ccxtでティッカー情報を取得
import ccxt
from pprint import pprint

bitflyer = ccxt.bitflyer()
ticker = bitflyer.fetch_ticker('BTC/JPY', params = {'product_code' : 'FX_BTC_JPY'} )
pprint(ticker)<jupyter_output>{'ask': 4425592.0,
 'askVolume': None,
 'average': None,
 'baseVolume': 8066.46025461,
 'bid': 4424499.0,
 'bidVolume': None,
 'change': None,
 'close': 4425692.0,
 'datetime': '2022-01-28T21:52:22.897Z',
 'high': None,
 'info': {'best_ask': '4425592.0',
          'best_ask_size': '0.02',
          'best_bid': '4424499.0',
          'best_bid_size': '0.04',
          'ltp': '4425692.0',
          'market_ask_size': '0.0',
          'market_bid_size': '0.0',
          'product_code': 'FX_BTC_JPY',
          'state': 'RUNNING',
          'tick_id': '13551749',
          'timestamp': '2022-01-28T21:52:22.897',
          'total_ask_depth': '170.02476421',
          'total_bid_depth': '397.81560699',
          'volume': '8070.80825461',
          'volume_by_product': '8066.46025461'},
 'last': 4425692.0,
 'low': None,
 'open': None,
 'percentage': None,
 'previousClose': None,
 'quoteVolume': None,
 'symbol': 'BTC/JPY',
 'timestamp': 1643406742897,
 'vwap': None}<jupyter_text>FXの証拠金残高を確認ccxtには、Bitflyerで BTC-FX の証拠金残高を取得する共通の関数がない  ccxt経由で直接apiを操作して情報を取得するには、以下の用にするして関数を作る取引所のAPIを使うためのコード  X）プライベートAPIかパブリックAPIか？  Y）メソッドはGET方式か？POST方式か？  Z）APIのリクエストURL（パス）は？  ->> 関数名 ： .X_Y_Z()  https://ryota-trade.com/?p=629<jupyter_code># 取引所のAPIを使うためのコード
# X）プライベートAPIかパブリックAPIか？
# Y）メソッドはGET方式か？POST方式か？
# Z）APIのリクエストURL（パス）は？
# ->> 関数名 ： .X_Y_Z()
# https://ryota-trade.com/?p=629
import ccxt
from pprint import pprint

bitflyer = ccxt.bitflyer()
bitflyer.apiKey = ''
bitflyer.secret = ''

collateral = bitflyer.private_get_getcollateral()
pprint(collateral)
# 取引所が対応している共通のcopy_contextの関数
import ccxt
bitflyer = ccxt.bitflyer()
method_list = bitflyer.has

for key, val in method_list.items():
    if val == True:
        print(key, val)
# 注文情報の取得
import ccxt
from pprint import pprint

bitflyer = ccxt.bitflyer()
bitflyer.apiKey = ''
bitflyer.secret = ''

# open_order:まだ約定していない注文のこと
order = bitflyer.fetch_open_orders(
    symbol = 'BTC/JPY', 
    params = {'product_code', 'FX_BTC_JPY'}
)
pprint(orders)
# 注文情報のID取得
import ccxt
from pprint import pprint

bitflyer = ccxt.bitflyer()
bitflyer.apiKey = ''
bitflyer.secret = ''

orders = bitflyer.fetch_open_orders(
    symbol = 'BTC/JPY',
    params = {'product_code' : 'FX_BTC_JPY'}
 )

 for o in orders:
     pprint(o['id'])
# 注文情報の状況を取得
import ccxt
from pprint import pprint

bitflyer = ccxt.bitflyer()
bitflyer.apikey = ''
bitflyer.secret = ''

orders = bitflyer.fetch_orders(
    symbol = 'BTC/JPY',
    params = {'product_code' : 'FX_BTC_JPY', 'count' : 10}
)

for o in orders:
    print(o['id'] + ' : 注文状況 ' + o['status'])
# 注文のキャンセル
bitflyer.cancel_order(
    symbol = 'BTC/JPY',
    id = ''
    params = {'product_code' : 'FX_BTC_JPY'}
)
# Cryptowatchからbitflyerのデータを取得
# ローソク足を取得
import requests
from datetime import datetime
import time

# 1分足
response = requests.get('https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc?periods=60')
response = response.json()
# 一つ前のローソク足を取得（終値が確定したものの最新）
# [-1]だと、終値がまだ確定していない
data = response['result']['60'][-2]

close_time = datetime.fromtimestamp(data[0]).strftime('%Y/%m/%d %H:%M')
open_price = data[1]
close_price = data[4]

print("時間: " + close_time
	+ " 始値: " + str(open_price)
	+ " 終値: " + str(close_price) )
# 10秒でデータを取って繰り返す。
import requests
from datetime import datetime
import time

while True:
    response = response.get('https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc?periods=60')
    
    data = response['result']['60'][-2]

    close_time = datetime.fromtimestamp(data[0]).strftime('%Y/%m/%d %H:%M')
    open_price = data[1]
    close_price = data[4]

    print("時間: " + close_time
        + " 始値: " + str(open_price)
        + " 終値: " + str(close_price))

    time.sleep(10)
# 上にループを抜けるコードがないと、以下のコードはグレーアウトする
y = 1 + 2
print(y)
# 更新された時だけprintする
import requests
from datetime import datetime
import time


response = requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc?periods=60")
response = response.json()

# 前回の時間を last_time に入れる
last_data = response["result"]["60"][-2]
last_time = datetime.fromtimestamp(last_data[0]).strftime('%Y/%m/%d %H:%M')
time.sleep(10)

while True:
    response = requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc?periods=60")
    response = response.json()

    data = response['result']['60'][-2]

    close_time = datetime.fromtimestamp(data[0]).strftime('%Y/%m/%d %H:%M')
    open_price = data[1]
    close_price = data[4]
    if close_time != last_time:
        print("時間: " + close_time
			+ " 始値: " + str(open_price)
			+ " 終値: " + str(close_price))

        last_time = close_time

    time.sleep(10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16182048040455121, 'fraction_numerical': 0.042667509481668774, 'mean_word_length': 4.5323426573426575, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 9, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '548432', 'license': 'CC0-1.0', 'n_tokens_mistral': 2990, 'n_tokens_neox': 2807, 'n_words': 413, 'path': 'my_tutorial/sp_1.ipynb', 'repo_name': 'coffeepot74/mlbot_tutorial', 'size': '6328'}