0% found this document useful (0 votes)
44 views

Generate and Execute

This document defines functions for an automated trading strategy using OANDA's API. It generates trading signals based on technical indicators like RSI, SMA, BBANDS calculated on historical candlestick data. When a signal is generated, it calculates the trade size based on the account balance and risk percentage. Finally, it places market orders with stop loss and take profit levels through OANDA's orders endpoint. The strategy runs in a loop to continuously generate signals and execute trades every hour.

Uploaded by

Andrei Nohai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Generate and Execute

This document defines functions for an automated trading strategy using OANDA's API. It generates trading signals based on technical indicators like RSI, SMA, BBANDS calculated on historical candlestick data. When a signal is generated, it calculates the trade size based on the account balance and risk percentage. Finally, it places market orders with stop loss and take profit levels through OANDA's orders endpoint. The strategy runs in a loop to continuously generate signals and execute trades every hour.

Uploaded by

Andrei Nohai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import pandas as pd

import numpy as np
import talib as ta
import oandapyV20
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import oandapyV20.endpoints.orders as orders
import time

# Initialize OANDA API client


client = API(access_token='your_access_token')

# Define currency pair and timeframe


currency_pair = 'EUR_USD'
timeframe = 'H1'

# Define trade size, risk management and stop loss


trade_size = 1000
risk_percentage = 0.7
stop_loss_pips = 50

# Define signal generation function


def generate_signal(df):
# Calculate indicators
df['rsi'] = ta.RSI(df['close'], timeperiod=14)
df['ma_50'] = ta.SMA(df['close'], timeperiod=50)
df['ma_200'] = ta.SMA(df['close'], timeperiod=200)
df['fib_23.6'] = df['high'].max() - 0.236 * (df['high'].max() -
df['low'].min())
df['fib_38.2'] = df['high'].max() - 0.382 * (df['high'].max() -
df['low'].min())
df['fib_61.8'] = df['high'].max() - 0.618 * (df['high'].max() -
df['low'].min())
df['upper_band'], df['middle_band'], df['lower_band'] = ta.BBANDS(df['close'],
timeperiod=20, nbdevup=2, nbdevdn=2)

# Generate signals
if df['rsi'].iloc[-1] > 70 and df['close'].iloc[-1] > df['ma_50'].iloc[-1] and
df['close'].iloc[-1] > df['ma_200'].iloc[-1] and df['close'].iloc[-1] >
df['fib_23.6'].iloc[-1] and df['close'].iloc[-1] > df['upper_band'].iloc[-1]:
return 'buy'
elif df['rsi'].iloc[-1] < 30 and df['close'].iloc[-1] < df['ma_50'].iloc[-1]
and df['close'].iloc[-1] < df['ma_200'].iloc[-1] and df['close'].iloc[-1] <
df['fib_61.8'].iloc[-1] and df['close'].iloc[-1] < df['lower_band'].iloc[-1]:
return 'sell'
else:
return 'hold'

# Define trade execution function


def execute_trade(signal):
# Get current market price
params = {
'instruments': currency_pair
}
prices = client.pricing.get(params=params)['prices']
price = prices[0]['closeoutAsk'] if signal == 'buy' else prices[0]
['closeoutBid']

# Calculate trade size based on available balance and desired risk


account_info = client.account.get(accountID=accountID)['account']
equity = account_info['balance']
risk = 0.7
trade_size = (equity * risk) // (stop_loss_distance * price)

# Define order parameters


order_params = {
'order': {
'price': None,
'stopLossOnFill': {
'price': None,
'timeInForce': 'GTC'
},
'takeProfitOnFill': {
'price': None,
'timeInForce': 'GTC'
},
'timeInForce': 'GTC',
'instrument': currency_pair,
'units': trade_size,
'type': 'MARKET',
'positionFill': 'DEFAULT'
}
}

# Set order price and stop loss/take profit levels based on signal
if signal == 'buy':
order_params['order']['price'] = price
order_params['order']['stopLossOnFill']['price'] = price -
stop_loss_distance = 0.0025 # 25 pips
order_params['order']['takeProfitOnFill']['price'] = price +
take_profit_distance = 0.0050 # 50 pips
else:
order_params['order']['price'] = price
order_params['order']['stopLossOnFill']['price'] = price +
stop_loss_distance = 0.0025 # 25 pips
order_params['order']['takeProfitOnFill']['price'] = price -
take_profit_distance = 0.0050 # 50 pips

# Execute order
r = orders.OrderCreate(accountID=accountID, data=order_params)
client.request(r)

while True:
# Generate signal
signal = generate_signal()

# Execute trade if signal is not 'hold'


if signal != 'hold':
execute_trade(signal)

# Wait for 1 hour before generating another signal


time.sleep(3600)

You might also like