A foreign currencies/forex trading management program.
pip install pytz numpy pandas finplot bs4 prompt_toolkit dateutil pushbullet.py
go to "src" folder and
python3 start.py
Index:
- TradingAgent and BrokerAPI
- BrokerAPI
- Account
- Order
- Trade
- Instrument
- NotificationServiceProvider
- TechnicalIndicators
- coin_wizard.historical_pair_data
You shall aquire your BrokerAPI from your TradingAgent start(), test(), train() functions as an entry point. Depended on your choice of launching TradingAgent.
class TradingAgent(object):
def __init__(self, agent_files_directory):
pass
def run(self, BrokerAPI):
# Can be here.
pass
def stop_running(self, BrokerAPI):
pass
def train(self, BrokerAPI):
# Can be here.
pass
def stop_training(self, BrokerAPI):
pass
def test(self, BrokerAPI):
# Or can be here.
pass
def stop_testing(self, BrokerAPI):
pass
Get the account object.
account = BrokerAPI.getAccount()
Get the instrument object.
# Get the EUR_USD instrument.
instrument = BrokerAPI.getInstrument('EUR_USD')
Order for an instrument with order and trade settings.
# Order 2 units EUR_USD instrument in the market immediately.
order = BrokerAPI.order('EUR_USD', {"type": "market"}, {"units": 2})
# Order stop order of EUR_USD instrument. With load of settings.
order = BrokerAPI.order('EUR_USD', {"type": "stop", "price": 2, "bound": 2.1}, {"units": 1, "take_profit": 2, "stop_lost": 0.5, "trailing_stop_distance": 0.001})
Get the notification_service_provider object.
nsp = BrokerAPI.getNotificationServiceProvider()
Register listener/callback for every loop of event-loop.
# Note that every times that the callback emitted BrokerAPI is passed as parameters.
def loop(BrokerAPI):
# do something here
pass
# With every loop of event-loop call loop() function.
BrokerAPI.onLoop(loop)
Register listener/callback for every 15 seconds.
# Note that every times that the callback emitted BrokerAPI is passed as parameters.
def loop15s(BrokerAPI):
# do something here
pass
# With every 15 seconds of event-loop call loop15s() function.
BrokerAPI.onEvery15Second(loop15s)
First, get the account object from BrokerAPI.
account = BrokerAPI.getAccount()
Get your account balance in float type.
balance = account.getBalance()
# For example 10000.0
Get your account balance in string type.
currency = account.getCurrency()
# For example "USD"
Get your account margin rate in float type.
margin_rate = account.getMarginRate()
# For example 0.02
Get your account margin available in float type.
margin_available = account.getMarginAvailable()
# For example 99980.0
Get your account margin used in float type.
margin_used = account.getMarginUsed()
# For example 20.0
Get your account unrealized profit&loss in float type.
unrealized_pl = account.getUnrealizedPL()
# For example -20.0
Get your account orders in list.
orders = account.getOrders()
# For example [order_object_1, order_object_2]
Get your account trades in list.
trades = account.getTrades()
# For example [trade_object_1]
First, you should get your order either from BrokerAPI.order(...params) or Account.getOrders()
# Order 2 units EUR_USD instrument in the market immediately.
order = BrokerAPI.order('EUR_USD', {"type": "market"}, {"units": 2})
orders = account.getOrders()
# For example [order_object_1, order_object_2]
Register listener/callback for order filled event.
# Note that every times that the callback emitted order and trade is passed as parameters.
def filled_listener(order, trade):
# do something here
pass
# When the order filled, call "filled_listener".
order.onFilled(filled_listener)
Register listener/callback for order filled event.
# Note that every times that the callback emitted order and reason(string type) is passed as parameters.
def canceled_listener(order, reason):
# do something here
pass
# When the order canceled, call "canceled_listener".
order.onCanceled(canceled_listener)
Cancel the order itself.
order.cancel()
Do not forget to register order canceled listener.
order.onCanceled(canceled_listener)
Get your order instrument name.
instrument_name = order.getInstrumentName()
# For example "EUR_USD"
Get your order's order settings.
order_settings = order.getOrderSettings()
# For example
# {
# "type": "market"
# }
Get your order's trade setting.
trade_settings = order.getTradeSettings()
# For example
# {
# "units": -7997.0,
# "current_units": -7996.0,
# "take_profit": 0.543,
# "stop_loss": 2.0,
# "trailing_stop_distance": 0.1
# }
First, you should get your order either from order.onFilled or Account.getTrades()
def filled_listener(order, trade):
# You get your trade of that order here.
pass
# When the order filled, call "filled_listener".
order.onFilled(filled_listener)
trades = account.getTrades()
# For example [trade_object_1, trade_object_2]
Register listener/callback for trade closed event.
# Note that every times that the callback emitted.
# trade, realized_pl, close_price, spread, timestamp is passed as parameters.
def closed_listener(self, trade, realized_pl, close_price, spread, timestamp):
# do something here
pass
# When the trade closed, call "closed_listener".
trade.onClosed(closed_listener)
Register listener/callback for trade closed event.
# Note that every times that the callback emitted.
# trade, units, realized_pl, close_price, spread, timestamp is passed as parameters.
# Different from Trade.onClosed, Trade.onReduced pass units parameters. For example: units = -1.0, units = 2.0.
def reduced_listener(trade, units, realized_pl, close_price, spread, timestamp):
# do something here
pass
# When the trade reduced, call "reduced_listener".
trade.onReduced(reduced_listener)
Close the trade itself.
trade.close()
Do not forget to register trade closed listener.
trade.onClosed(closed_listener)
Reduce 10 units of long position trade. Both accepted.
trade.reduce(-10)
trade.reduce(10)
Reduce 10 units of short position.
trade.reduce(10)
Do not forget to register trade closed listener.
trade.onClosed(closed_listener)
Get your trade instrument name.
instrument_name = trade.getInstrumentName()
# For example "EUR_USD"
Get your trade open price.
price = trade.getOpenPrice()
# For example 1.4325
Get your trade's trade setting.
trade_settings = trade.getTradeSettings()
# For example
# {
# "units": -7997.0,
# "current_units": -7996.0,
# "take_profit": 0.543,
# "stop_loss": 2.0,
# "trailing_stop_distance": 0.1
# }
Get your trade unrealized profit&loss.
unrealized_pl = trade.getUnrealizedPL()
# For example -21.011
First, get the account object from BrokerAPI.
# Get the EUR_USD instrument.
instrument = BrokerAPI.getInstrument('EUR_USD')
Get instrument current closeout bid, ask and timestamp.
bid, ask, timestamp = instrument.getCurrentCloseoutBidAsk()
# For example: 1.19289, 1.19303, datetime.datetime(2021, 3, 15, 12, 15, 29, 271891, tzinfo=tzutc())
Get instrument active 1m candle dataframe(pandas).
the_candle_df = instrument.getActive1MCandle()
# Return pandas dataframe with below fields:
# timestamp, open, high, low, close
# Note that timestamp is in utc iso format
Get instrument active recent 1m candle dataframe(pandas).
# Get 1000 candles.
candles_df = instrument.getRecent1MCandles(1000)
# Return pandas 1000 rows dataframe with below fields:
# timestamp, open, high, low, close
# Note that timestamp is in utc iso format
Check if such instrument is tradable.
tradable = instrument.isTradable()
# For example: False
First, get the notification_service_provider object from BrokerAPI.
nsp = BrokerAPI.getNotificationServiceProvider()
Push a notification immediately.
# Push notification with title and context.
nsp.pushImmediately('Title1', 'Hello')
Add a notification line for later push. (Not yet sent/push)
# Add a line.
nsp.addLine('Hello')
Push accumulated notification lines with title.
# Add a line.
nsp.addLine('Hello')
# Push.
nsp.push('Title1')
In your trading agent
ti = BrokerAPI.TechnicalIndicators
Moving average
Exponential moving average
Moving average convergence divergence
Rate of change
Momentum
Relative strength index ma
Relative strength index ema
Bollinger bands
Commodity channel index
In your trading agent
import coin_wizard.historical_pair_data as historical_pair_data
Get your historical data in numpy format with utc timestamp from 1970, 1, 1.
# Get historical data in with eastern time setup.
historical_pair_data.get_historical_pair_data('eurusd', datetime(2021, 1, 8, 0, 0), datetime(2021, 1, 11, 23, 59))
# Get historical data in with eastern time setup.
import pytz
eastern = pytz.timezone('US/Eastern')
historical_pair_data.get_historical_pair_data('eurusd', eastern.localize(datetime(2021, 1, 8, 0, 0)), eastern.localize(datetime(2021, 1, 11, 23, 59)))
Get your historical data in pandas format. With default UTC timezone.
# Get historical data in with eastern time setup.
historical_pair_data.get_historical_pair_data_pandas('eurusd', datetime(2021, 1, 8, 0, 0), datetime(2021, 1, 11, 23, 59))
# Get historical data in with eastern time setup. And too output with timezone 'US/Eastern' as the latest parameter.
import pytz
eastern = pytz.timezone('US/Eastern')
historical_pair_data.get_historical_pair_data_pandas('eurusd', eastern.localize(datetime(2021, 1, 8, 0, 0)), eastern.localize(datetime(2021, 1, 11, 23, 59)), 'US/Eastern')
Plot your historical data.
# Plot historical data in with eastern time setup.
import pytz
eastern = pytz.timezone('US/Eastern')
historical_pair_data.plot_historical_pair_data('eurusd', eastern.localize(datetime(2021, 1, 8, 0, 0)), eastern.localize(datetime(2021, 1, 11, 23, 59)), 'US/Eastern')