TDD Example: Rule #1 Trading with Alpaca (2)
Let's see how we can refactor our application before moving on.
You now have a working client for the Alpaca Paper Trading API [1].
What TDD is about is: fearless refactoring, and making steady progress, sometimes in tiny steps if necessary.
Just today, being able to proceed in tiny steps saved me at work.
One day, trying to refactor the interface to my application, I fell into a series of test failures I couldn't fix.
On the next day, I decided to restore the state to the previous working configuration. I was glad I had committed the green state of the tests before diving into the refactoring.
I reverted the changes, made my steps tinier and more careful, and started again.
This time, it went fluently, and I finished the day with the application working, and with tests all passing.
As a bonus, I left a test that would test the next feature to be implemented. A small modification of that test will turn it from green to red, and allow me to kickstart the implementation process.
That will save me time reminding myself, what the next goal on the list was.
The steps of TDD are:
- RED: Write a failing test, where "not compiling" matches the definition of "failing".
- GREEN: Make the test pass - preferably using the simplest possible change.
- REFACTOR: Remove duplication, feel free to generalize your approach.
- In this step, use the test to verify the changes make sense.
Our previous test was RED first.
When you registered with Alpaca, and saved the keys in creds.py
, it became GREEN. What about refactoring?
The helpful question to ask here is: do we see any duplication we could remove at this point?
Let's check the code again:
from alpaca.trading.client import TradingClient
from creds import api_key, secret_key
alpaca = TradingClient(
api_key, secret_key, paper=True
)
Since api_key
and secret_key
appear twice in our code, let's change that.
import creds
alpaca = TradingClient(
creds.api_key,
creds.secret_key,
paper=True
)
This time, "creds" repeats three times in our code. HOwever, we use a single object to refer to the credentials. That should make it easier for us to replace the credentials in case we need to.
I found the naming in Alpaca docs a bit confusing: api_key
already sounds as if it was a "secret".
Many applications require a single key, called an "API key", to control the access to their services, while here, api_key
is more like a login.
Now that we are done with the refactoring, let's add a test for the next simplest feature we will need. We will do that in the next issue.