SlideShare a Scribd company logo
1 of 20
Download to read offline
Training the agent for trading use
Interactive Broker python api
How to build your own agent
● Modeling
● Training
● Backtesting
● Real-time paper trading
How to build the model
Market
Environment
Observation
Agent
Action
Reward
How to build the model
● Input : State t (Observation)
● Output : Action (Price Order, Limit Order, long or short, ask or bid)
● Reward
● St, At, Rt, St+1, At+1, Rt+1……
How to build the model
● Model architecture
○ FNN
○ CNN
○ RNN(LSTM, GRU)
○ CNN + RNN(LSTM, GRU)
○ UFCNN
How to build the model
● Objective Function
● Maximize Total Reward
● Set correct answer using historical data (ex : future>3% buy...)
○ RL way Rt+1*gamma + Rt+2*gamma^2 …
● Reinforcement Learning
Open Ai Gym
● https://github.com/openai/gym
● https://gym.openai.com/evaluations/eval_glkKKInTm6GlmcOQRZuhQ
import gym
env = gym.make("Breakout-v0")
observation = env.reset()
for _ in range(1000):
env.render()
action = env.action_space.sample() # your agent here (this takes random actions)
observation, reward, done, info = env.step(action)
Trading Gym
● https://github.com/Yvictor/TradingGym
import random
import pandas as pd
import trading_env
df = pd.read_hdf('dataset/SGXTW.h5', 'STW')
env = trading_env.make(obs_data_len=256, step_len=128,
df=df, fee=0.1, max_position=5, deal_col_name='Price',
feature_names=['Price', 'Volume', 'Ask_price','Bid_price',
'Ask_deal_vol','Bid_deal_vol', 'Bid/Ask_deal', 'Updown'])
env.reset()
env.render()
state, reward, done, info = env.step(random.randrange(3))
### random choice action and show the transaction detail
for i in range(500):
state, reward, done, info = env.step(random.randrange(3))
env.render()
if done:
break
env.transaction_details
Trading Gym
● Build your own agent
class YourAgent:
def __init__(self):
# build your network and so on
pass
def choice_action(self, state):
## your rule base condition or your max Qvalue action or Policy Gradient action
# action=0 -> do nothing
# action=1 -> buy 1 share
# action=2 -> sell 1 share
## in this testing case we just build a simple random policy
return np.random.randint(3)
Trading Gym
● backtesting
agent = YourAgent()
state = env.backtest()
done = False
while not done:
state, reward, done, info = env.step(agent.choice_action(state))
#print(state, reward)
#env.render()
if done:
break
env.transaction_details
Trading Gym
● Rule base usage
env = trading_env.make(obs_data_len=10, step_len=1,
df=df, fee=0.1, max_position=5, deal_col_name='Price',
feature_names=['Price', 'MA'],
fluc_div=100.0)
class MaAgent:
def __init__(self):
pass
def choice_action(self, state):
if state[-1][0] > state[-1][1] and state[-2][0] <= state[-2][1]:
return 1
elif state[-1][0] < state[-1][1] and state[-2][0] >= state[-2][1]:
return 2
else:
return 0
# then same as above
Real-time paper trading
● Interactive Broker API
○ Cross platform
○ Need to open TWS or IB gateway
○ C++, C#, Java, Python, VB …
○ http://interactivebrokers.github.io/#
Real-time paper trading
● Official IB python API
○ Requirements : python 3.1 or higher, TWS 952.x or higher
○ Install API for python https://git.io/vHjng
wget http://interactivebrokers.github.io/downloads/twsapi_macunix.973.02.zip
unzip twsapi_macunix.973.02.zip
cd IBJts/source/pythonclient
python setup.py install
Cd ../../smaples/Python/Testbed/
python Program.py -p 4002
Real-time paper trading
● ibapi.client.EClient, ibapi.wrapper.EWrapper
from ibapi.client import EClient
from ibapi.wrapper import EWrapper, iswrapper
class TWSClient(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, wrapper=self)
client = TWSClient()
client.connect("127.0.0.1", 4002, clientId=1)
print("serverVersion:%s connectionTime:%s" % (client.serverVersion(),
client.twsConnectionTime()))
Real-time paper trading
● Contract
○ contract = ibapi.contract.Contract()
contract.symbol = "EUR"
contract.secType = "CASH"
contract.currency = "GBP"
contract.exchange = "IDEALPRO"
○ contract = ibapi.contract.Contract()
contract.symbol = 'TSLA'
contract.secType = 'STK'
contract.currency = 'USD'
contract.exchange = 'SMART'
Real-time paper trading
● Order
○ Market
○ Market If Touched
○ Market On Close, Open
○ Limit Order
○ Limit if Touched
○ https://interactivebrokers.github.io/tws-api/basic_orders.html#gsc.tab=
0
Real-time paper trading
● Market Data
○ Live Market
○ L1
■ Stocks, Futures and others , Frequency : 250 ms
■ US Options Frequency : 100 ms
○ L2
○ Historical Data
○ Real Time Bars
Real-time paper trading
● Accounts
○ Positions
○ Summary
○ Updates
○ https://interactivebrokers.github.io/tws-api/account_portfolio.html#g
sc.tab=0
Real-time paper trading with Trading GYM
WIP
DEMO

More Related Content

Similar to Training the agent for trading use Interactive Broker python api

Map reduce: beyond word count
Map reduce: beyond word countMap reduce: beyond word count
Map reduce: beyond word countJeff Patti
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTaegyun Jeon
 
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...ETS Asset Management Factory
 
Reinfrocement Learning
Reinfrocement LearningReinfrocement Learning
Reinfrocement LearningNatan Katz
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
The SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationThe SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationJean-Jacques Dubray
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RRsquared Academy
 
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...Chetan Khatri
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
PyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticePyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticeSeomgi Han
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트기룡 남
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowRomain Dorgueil
 
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...GeeksLab Odessa
 

Similar to Training the agent for trading use Interactive Broker python api (20)

Map reduce: beyond word count
Map reduce: beyond word countMap reduce: beyond word count
Map reduce: beyond word count
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager ExecutionTensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
 
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
Python + Tensorflow: how to earn money in the Stock Exchange with Deep Learni...
 
Reinfrocement Learning
Reinfrocement LearningReinfrocement Learning
Reinfrocement Learning
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
The SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationThe SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and Computation
 
Xgboost
XgboostXgboost
Xgboost
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In R
 
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...
TransmogrifAI - Automate Machine Learning Workflow with the power of Scala an...
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
(Alpha) Zero to Elo (with demo)
(Alpha) Zero to Elo (with demo)(Alpha) Zero to Elo (with demo)
(Alpha) Zero to Elo (with demo)
 
PyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticePyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in Practice
 
Deep RL.pdf
Deep RL.pdfDeep RL.pdf
Deep RL.pdf
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
DataScienceLab2017_Оптимизация гиперпараметров машинного обучения при помощи ...
 
Code optimization
Code optimization Code optimization
Code optimization
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Training the agent for trading use Interactive Broker python api

  • 1. Training the agent for trading use Interactive Broker python api
  • 2. How to build your own agent ● Modeling ● Training ● Backtesting ● Real-time paper trading
  • 3. How to build the model Market Environment Observation Agent Action Reward
  • 4. How to build the model ● Input : State t (Observation) ● Output : Action (Price Order, Limit Order, long or short, ask or bid) ● Reward ● St, At, Rt, St+1, At+1, Rt+1……
  • 5. How to build the model ● Model architecture ○ FNN ○ CNN ○ RNN(LSTM, GRU) ○ CNN + RNN(LSTM, GRU) ○ UFCNN
  • 6. How to build the model ● Objective Function ● Maximize Total Reward ● Set correct answer using historical data (ex : future>3% buy...) ○ RL way Rt+1*gamma + Rt+2*gamma^2 … ● Reinforcement Learning
  • 7. Open Ai Gym ● https://github.com/openai/gym ● https://gym.openai.com/evaluations/eval_glkKKInTm6GlmcOQRZuhQ import gym env = gym.make("Breakout-v0") observation = env.reset() for _ in range(1000): env.render() action = env.action_space.sample() # your agent here (this takes random actions) observation, reward, done, info = env.step(action)
  • 8. Trading Gym ● https://github.com/Yvictor/TradingGym import random import pandas as pd import trading_env df = pd.read_hdf('dataset/SGXTW.h5', 'STW') env = trading_env.make(obs_data_len=256, step_len=128, df=df, fee=0.1, max_position=5, deal_col_name='Price', feature_names=['Price', 'Volume', 'Ask_price','Bid_price', 'Ask_deal_vol','Bid_deal_vol', 'Bid/Ask_deal', 'Updown']) env.reset() env.render() state, reward, done, info = env.step(random.randrange(3)) ### random choice action and show the transaction detail for i in range(500): state, reward, done, info = env.step(random.randrange(3)) env.render() if done: break env.transaction_details
  • 9. Trading Gym ● Build your own agent class YourAgent: def __init__(self): # build your network and so on pass def choice_action(self, state): ## your rule base condition or your max Qvalue action or Policy Gradient action # action=0 -> do nothing # action=1 -> buy 1 share # action=2 -> sell 1 share ## in this testing case we just build a simple random policy return np.random.randint(3)
  • 10. Trading Gym ● backtesting agent = YourAgent() state = env.backtest() done = False while not done: state, reward, done, info = env.step(agent.choice_action(state)) #print(state, reward) #env.render() if done: break env.transaction_details
  • 11. Trading Gym ● Rule base usage env = trading_env.make(obs_data_len=10, step_len=1, df=df, fee=0.1, max_position=5, deal_col_name='Price', feature_names=['Price', 'MA'], fluc_div=100.0) class MaAgent: def __init__(self): pass def choice_action(self, state): if state[-1][0] > state[-1][1] and state[-2][0] <= state[-2][1]: return 1 elif state[-1][0] < state[-1][1] and state[-2][0] >= state[-2][1]: return 2 else: return 0 # then same as above
  • 12. Real-time paper trading ● Interactive Broker API ○ Cross platform ○ Need to open TWS or IB gateway ○ C++, C#, Java, Python, VB … ○ http://interactivebrokers.github.io/#
  • 13. Real-time paper trading ● Official IB python API ○ Requirements : python 3.1 or higher, TWS 952.x or higher ○ Install API for python https://git.io/vHjng wget http://interactivebrokers.github.io/downloads/twsapi_macunix.973.02.zip unzip twsapi_macunix.973.02.zip cd IBJts/source/pythonclient python setup.py install Cd ../../smaples/Python/Testbed/ python Program.py -p 4002
  • 14. Real-time paper trading ● ibapi.client.EClient, ibapi.wrapper.EWrapper from ibapi.client import EClient from ibapi.wrapper import EWrapper, iswrapper class TWSClient(EWrapper, EClient): def __init__(self): EClient.__init__(self, wrapper=self) client = TWSClient() client.connect("127.0.0.1", 4002, clientId=1) print("serverVersion:%s connectionTime:%s" % (client.serverVersion(), client.twsConnectionTime()))
  • 15. Real-time paper trading ● Contract ○ contract = ibapi.contract.Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "GBP" contract.exchange = "IDEALPRO" ○ contract = ibapi.contract.Contract() contract.symbol = 'TSLA' contract.secType = 'STK' contract.currency = 'USD' contract.exchange = 'SMART'
  • 16. Real-time paper trading ● Order ○ Market ○ Market If Touched ○ Market On Close, Open ○ Limit Order ○ Limit if Touched ○ https://interactivebrokers.github.io/tws-api/basic_orders.html#gsc.tab= 0
  • 17. Real-time paper trading ● Market Data ○ Live Market ○ L1 ■ Stocks, Futures and others , Frequency : 250 ms ■ US Options Frequency : 100 ms ○ L2 ○ Historical Data ○ Real Time Bars
  • 18. Real-time paper trading ● Accounts ○ Positions ○ Summary ○ Updates ○ https://interactivebrokers.github.io/tws-api/account_portfolio.html#g sc.tab=0
  • 19. Real-time paper trading with Trading GYM WIP
  • 20. DEMO