![見出し画像](https://assets.st-note.com/production/uploads/images/55461409/rectangle_large_type_2_f2ed9e8f3b7c8fc50bc8a8f00e76252e.jpeg?width=1200)
OANDAでFXの自動トレード作成講座
本記事は何を学びますか?
❶アプリはWEBアプリとなりますので、WEB系のバックエンドで必要なデータベースやフロントエンドなどFlaskを使ったフレームワークを学ぶことができます。
❷FXの自動トレードの基本を身につけることができます。
❸株式投資やFXなどにも使えるテクニカル分析を身に付けることができます。
事前知識:
❶Pythonの基礎
❷HTML, JQuery, SQL, MySQL、Json、Web Serverなどを扱いますので、WEB系の基本知識があると良いかと思います。
❸Oandaのアカウント開設が必要です。
初めに
FXとは
証拠金を業者に預託し、主に差金決済による通貨の売買を行なう取引をいう。「FX」、「通貨証拠金取引」、「外国為替保証金取引」などともいう。FXはForeign eXchange=外国為替の略に由来している。海外ではForex と呼ばれることが多い。
OANDAとは
FX取引とCFD取引ならOANDA JAPAN。設立24年で、世界7か国にオフィスがあり、MT4やMT5、API、fxTradeなど多様の取引プラットフォームが利用可能。
環境設定
AWS Cloud9利用
初心者は下記ご参考ください。
https://note.com/shushuitie/n/n212d63d8da9d
必要なライブラリを導入
sudo pip install dict2obj==1.2.0
sudo pip install Flask==1.0.2
sudo pip install numpy==1.16.0
sudo pip install oandapyV20==0.6.3
sudo pip install omitempty==0.1.1
sudo pip install python-dateutil==2.8.0
sudo pip install requests==2.23.0
sudo pip install SQLAlchemy==1.3.7c
注意点
#Ta-Lib インストール
#cloud9のターミナルで以下を実行
wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
tar -zxvf ta-lib-0.4.0-src.tar.gz
cd ta-lib
./configure --prefix=/usr
make
sudo make install
sudo bash -c "echo "/usr/local/lib64" >> /etc/ld.so.conf"
sudo /sbin/ldconfig
sudo pip install ta-lib
Oanda API
❶パラメータ設定
settings.ini ファイル 新規作成
[oanda]
account_id = XXX-XXX-XXXXXXXX-XXX
access_token = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
settings.ini 内容を読み込みファイル settings.py 新規作成
import configparser
conf = configparser.ConfigParser()
conf.read('settings.ini')
account_id = conf['oanda']['account_id']
access_token = conf['oanda']['access_token']
main.py 実行ファイル 新規作成
import logging
import sys
import settings
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
if __name__ == "__main__":
print(settings.account_id)
print(settings.access_token)
❷アカウントのAPI申請
❸アカウントのバランス取得
oanda.py 取引所専用ファイル 新規作成
import logging
from oandapyV20 import API #token認証用
from oandapyV20.endpoints import accounts #アカウント情報取得用
from oandapyV20.exceptions import V20Error
logger = logging.getLogger(__name__)
class Balance(object):
def __init__(self, currency, available):
self.currency = currency
self.available = available
class APIClient(object):
def __init__(self, access_token, account_id, environment='practice'):
self.access_token = access_token
self.account_id = account_id
self.client = API(access_token=access_token, environment=environment)
def get_balance(self) -> Balance:
req = accounts.AccountSummary(accountID=self.account_id)
try:
resp = self.client.request(req)
except V20Error as e:
logger.error(f'action=get_balance error={e}')
raise
available = float(resp['account']['balance'])
currency = resp['account']['currency']
return Balance(currency, available)
main.py Balance内容追加する ソース変更
import logging
import sys
from oanda.oanda import APIClient
import settings
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
if __name__ == "__main__":
api_client = APIClient(settings.access_token, settings.account_id)
balance = api_client.get_balance()
print(balance.currency)#通貨
print(balance.available)#可用残高
❹プライス情報取得
oanda.py 価額情報内容を追加する ソース変更
from datetime import datetime
import logging
import dateutil.parser
from oandapyV20 import API
from oandapyV20.endpoints import accounts
from oandapyV20.endpoints.pricing import PricingInfo
from oandapyV20.exceptions import V20Error
logger = logging.getLogger(__name__)
class Balance(object):
def __init__(self, currency, available):
self.currency = currency
self.available = available
class Ticker(object):
def __init__(self, product_code, timestamp, bid, ask, volume):
self.product_code = product_code
self.timestamp = timestamp
self.bid = bid
self.ask = ask
self.volume = volume
class APIClient(object):
def __init__(self, access_token, account_id, environment='practice'):
self.access_token = access_token
self.account_id = account_id
self.client = API(access_token=access_token, environment=environment)
def get_balance(self) -> Balance:
req = accounts.AccountSummary(accountID=self.account_id)
try:
resp = self.client.request(req)
except V20Error as e:
logger.error(f'action=get_balance error={e}')
raise
available = float(resp['account']['balance'])
currency = resp['account']['currency']
return Balance(currency, available)
def get_ticker(self, product_code) -> Ticker:
params = {
'instruments': product_code
}
req = PricingInfo(accountID=self.account_id, params=params)
try:
resp = self.client.request(req)
except V20Error as e:
logger.error(f'action=get_ticker error={e}')
raise
timestamp = datetime.timestamp(
dateutil.parser.parse(resp['time']))
price = resp['prices'][0]
instrument = price['instrument']
bid = float(price['bids'][0]['price'])
ask = float(price['asks'][0]['price'])
volume = 11111 #仮入力
return Ticker(instrument, timestamp, bid, ask, volume)
main.py price内容追加する ソース変更
ここから先は
58,978字
¥ 1,998
期間限定!Amazon Payで支払うと抽選で
Amazonギフトカード5,000円分が当たる
Amazonギフトカード5,000円分が当たる
この記事が気に入ったらチップで応援してみませんか?